python 爬取价格
Python是一种非常合适爬取数据的编程语言。如果您需要获得某些商品的价格信息,Python可以帮助您轻松爬取这些信息。接下来是使用Python爬取价格的方法。
import requests from bs4 import BeautifulSoup url = 'https://www.amazon.cn/s?k=iphone' 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'} res = requests.get(url, headers=headers) soup = BeautifulSoup(res.text, 'html.parser') items = soup.find_all('div', {'class': 's-result-item'}) for item in items: try: price = item.find('span', {'class': 'a-price-whole'}).text.strip() print(price) except: pass
首先,我们导入了Python中的requests和BeautifulSoup库。
然后,我们指定了目标网站的URL,并设置了要求头。这是非常重要的,由于一些网站会避免机器人访问它们的网站。如果我们没有设置要求头,我们的要求将被谢绝。
接下来,我们使用requests库发送要求,并使用BeautifulSoup库解析HTML。我们使用find_all函数查找包括所需信息的HTML标签。
最后,我们循环打印每一个商品的价格信息。
在运行代码之前,确保您已安装了requests和BeautifulSoup库。您可使用以下命令在命令行中安装它们:
pip install requests
pip install beautifulsoup4
现在,您可使用这个简单的Python程序爬取您需要的价格数据。
文章来源:丸子建站
文章标题:python 爬取价格
https://www.wanzijz.com/view/75123.html