python爬取网易汽车首页内容
时间: 2023-08-12 13:08:51 浏览: 36
可以使用Python中的requests库和BeautifulSoup库来爬取网易汽车首页内容。具体步骤如下:
1.导入必要的库
```python
import requests
from bs4 import BeautifulSoup
```
2.发送请求,获取响应内容
```python
url = 'https://auto.163.com/'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
response = requests.get(url, headers=headers)
```
3.解析HTML内容
```python
soup = BeautifulSoup(response.content, 'html.parser')
```
4.从HTML中提取需要的内容
```python
# 获取新闻标题
titles = soup.select('.title')
for title in titles:
print(title.text)
# 获取新闻链接
links = soup.select('.title > a')
for link in links:
print(link['href'])
# 获取新闻图片链接
imgs = soup.select('.news-item > .wrap > img')
for img in imgs:
print(img['src'])
```
完整代码如下:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://auto.163.com/'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.content, 'html.parser')
# 获取新闻标题
titles = soup.select('.title')
for title in titles:
print(title.text)
# 获取新闻链接
links = soup.select('.title > a')
for link in links:
print(link['href'])
# 获取新闻图片链接
imgs = soup.select('.news-item > .wrap > img')
for img in imgs:
print(img['src'])
```