python 爬大众点评
Python 是一种很好用的编程语言,能够处理各种任务,包括网页爬取。这里我们将介绍怎样使用 Python 爬取大众点评网站。
import requests
from bs4 import BeautifulSoup
url = 'https://www.dianping.com/citylist/citylist?source=2'
header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36'}
response = requests.get(url, headers=header)
soup = BeautifulSoup(response.text, 'html.parser')
cities = soup.select('div.secondary-category >ul >li >a')
for city in cities:
print(city.get('title'))
上述代码首先导入了 requests 和 BeautifulSoup 模块,创建了一个 url 变量,用于指定需要爬取的大众点评网址。然后添加了一个 header,假装成浏览器。接着,使用 requests 库中的 get 方法得到了该网址内容,并用 BeautifulSoup 将其解析为一个 HTML 文件。
接下来,我们使用 select 方法从解析后的 HTML 当选择出我们需要的元素。这里我们选择城市的链接,它们都在 <div class="secondary-category"> 标签内。使用 for 循环,遍历这些链接,并使用 get 方法得到它们的 title 属性值,最后打印出城市名。
以上就是使用 Python 爬取大众点评的方法了。
文章来源:丸子建站
文章标题:python 爬大众点评
https://www.wanzijz.com/view/74452.html