使用Python写一个爬取商品价格的程式
时间: 2023-05-24 11:05:31 浏览: 43
以下是一个简单的Python爬虫程序,用于爬取商品价格:
```python
import requests
from bs4 import BeautifulSoup
def get_price(url):
# 发送HTTP GET请求
r = requests.get(url)
# 将HTML页面解析为BeautifulSoup对象
soup = BeautifulSoup(r.text, 'html.parser')
# 找到商品价格
price = soup.find('span', {'class':'price'}).text
# 返回价格
return price
# 测试程序
url = 'https://www.example.com/product/123'
price = get_price(url)
print('Price:', price)
```
这个程序使用requests库向指定URL发送GET请求,并使用BeautifulSoup库解析HTML页面。它将在HTML中查找包含商品价格的元素,并返回价格。在这个程序中,我们假设商品价格位于“span”元素中,而且具有“price”类名。实际中,你可能需要根据你爬取的网站进行适当的调整。
相关问题
使用python写一个爬取百度图片的爬虫
好的,以下是使用Python编写爬取百度图片的爬虫的代码:
```python
import requests
import re
def get_img_urls(keyword, num):
imgs = []
for i in range(num):
url = f'https://image.baidu.com/search/acjson?tn=resultjson_com&ipn=rj&word={keyword}&pn={i * 30}&rn=30'
response = requests.get(url)
img_urls = re.findall(r'"thumbURL":"(.*?)",', response.text)
imgs += img_urls
return imgs
def download_imgs(keyword, num):
img_urls = get_img_urls(keyword, num)
for i, url in enumerate(img_urls):
response = requests.get(url)
with open(f'{keyword}_{i}.jpg', 'wb') as f:
f.write(response.content)
print(f'Saved {keyword}_{i}.jpg')
if __name__ == '__main__':
download_imgs('猫', 10)
```
这个爬虫可以通过搜索关键词来爬取百度图片,并下载到本地。
使用Python写一端爬取商品价格的代码
好的,下面是一个简单的 Python 爬虫代码,它可以爬取商品价格。
首先,我们需要安装两个库:`requests` 和 `BeautifulSoup`。`requests` 库用于发送 HTTP 请求,而 `BeautifulSoup` 库用于解析 HTML 网页。
安装方法:
```
pip install requests
pip install beautifulsoup4
```
然后,我们可以使用以下代码来爬取商品价格:
```python
import requests
from bs4 import BeautifulSoup
# 要爬取的商品页面的 URL
url = "http://www.example.com/product-page.html"
# 发送 HTTP 请求,获取网页内容
response = requests.get(url)
# 使用 BeautifulSoup 解析网页内容
soup = BeautifulSoup(response.text, "html.parser")
# 查找商品价格所在的标签
price_tag = soup.find("span", class_="price")
# 获取标签中的价格文本
price_text = price_tag.text
# 将价格文本转换为数字
price = float(price_text)
print(price)
```
上面的代码首先发送 HTTP 请求来获取商品页面的内容,然后使用 BeautifulSoup 解析网页内容,最后查找商品价格所在的标签并获取价格文本。最后,将价格文本转换为数字并打印出来。
请注意,上面的代码仅作为示例,实际使用时可能需要根据实际情况进行修改。例如,你可能需要处
相关推荐















