python爬取爬取今日头条的新闻标题
时间: 2023-09-26 12:08:13 浏览: 132
您好!可以使用Python中的requests和beautifulsoup4库来实现爬取今日头条的新闻标题。具体步骤如下:
1. 导入requests和beautifulsoup4库
```python
import requests
from bs4 import BeautifulSoup
```
2. 设置请求头,模拟浏览器访问
```python
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'}
```
3. 发送请求,获取网页内容
```python
url = 'https://www.toutiao.com/'
response = requests.get(url, headers=headers)
html = response.text
```
4. 解析网页内容,获取新闻标题
```python
soup = BeautifulSoup(html, 'html.parser')
titles = soup.select('.title-box a')
for title in titles:
print(title.text.strip())
```
完整代码如下:
```python
import requests
from bs4 import BeautifulSoup
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'}
url = 'https://www.toutiao.com/'
response = requests.get(url, headers=headers)
html = response.text
soup = BeautifulSoup(html, 'html.parser')
titles = soup.select('.title-box a')
for title in titles:
print(title.text.strip())
```
希望这个回答能够帮到您!
阅读全文