从大众点评中爬取芜湖市景点地名的python代码
时间: 2023-09-15 14:18:52 浏览: 48
以下是使用Python爬取大众点评芜湖市景点地名的代码示例:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://www.dianping.com/wuhu/ch10/g101'
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.36 Edge/16.16299'
} # 设置请求头
r = requests.get(url, headers=headers)
soup = BeautifulSoup(r.text, 'html.parser')
spot_list = soup.find_all('div', class_='tit')
for spot in spot_list:
print(spot.get_text().strip())
```
解释:
1. 首先指定要爬取的网址为https://www.dianping.com/wuhu/ch10/g101,即大众点评芜湖市景点页面;
2. 设置请求头,模拟浏览器访问;
3. 发送GET请求,获取响应内容;
4. 使用BeautifulSoup解析HTML,提取所有景点名称所在的`<div>`标签,class属性为`tit`;
5. 遍历每个景点名称标签,使用`get_text()`方法获取标签内的文本内容并去除首尾空格,输出到控制台。
注意:为了防止网站反爬虫,建议在请求头中加入一些随机的参数,如随机生成的User-Agent,或者使用代理IP。