我试着从BeautifulSoup网站上提取不同的信息,比如产品的标题和价格。
我用不同的urls做这件事,用for...in...
循环这些urls。在这里,我将提供一个没有循环的片段。
from bs4 import BeautifulSoup
import requests
import csv
url= 'https://www.mediamarkt.ch/fr/product/_lg-oled65gx6la-1991479.html'
html_content = requests.get(url).text
soup = BeautifulSoup(html_content, "lxml")
price = soup.find('meta', property="product:price:amount")
title = soup.find("div", {"class": "flix-model-name"})
title2 = soup.find('div', class_="flix-model-name")
title3 = soup.find("div", attrs={"class": "flix-model-name"})
print(price['content'])
print(title)
print(title2)
print(title3)
因此,从这个网址lg-oled65gx6la-1991479.html,我不是要提取产品编号。我找到的唯一地方是div class="flix-model-name"
。然而,我完全无法达到它。我尝试了不同的方式来访问title
、title2
、title3
中的输出,但是输出none
总是这样。
我是个初学者,所以我想我可能错过了一些基本的东西.如果是的话,请原谅我。
欢迎任何帮助!事先非常感谢!
为了获取信息,我想在每个url中追加数据并将它们写到CSV文件中,如下所示:
for url in urls:
html_content = requests.get(url).text
soup = BeautifulSoup(html_content, "lxml")
row=[]
try:
# title = YOUR VERY WELCOMED ANSWER
prices = soup.find('meta', property="product:price:amount")
row = (title.text+','+prices['content']+'\n')
data.append(row)
except:
pass
file = open('database.csv','w')
i = 0
while i < (len(data)):
file.write(data[i])
i +=1
file.close()
非常感谢您的帮助!
大卫
发布于 2020-10-28 14:24:59
尝试下面的方法-- 请求 --当涉及到请求时,使用简单、简单、可靠、快速和更少的代码。我已经从网站本身获取API URL后,检查了谷歌铬浏览器的网络部分。
下面的脚本到底在做什么:
首先,它将接受API,根据2个动态参数(产品和类别)创建URL,然后执行获取数据的请求。
获得数据后,脚本将使用json.loads库解析JSON数据。最后,对产品列表进行逐个迭代,打印出按品牌、名称、产品编号、单价等两个类别划分的'box1_ProductToProduct‘和'box2_KategorieTopseller’的细节。同样,您可以通过查看API调用来添加更多细节。
import json
import requests
from urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
def scrap_product_details():
PRODUCT = 'MMCH1991479' #Product number
CATEGORY = '680942' #Category number
URL = 'https://www.mediamarkt.ch/rde_server/res/MMCH/recomm/product_detail/sid/WACXyEbIf3khlu6FcHlh1B1?product=' + PRODUCT + '&category=' + CATEGORY # dynamic URL
response = requests.get(URL,verify = False) #GET request to fetch the data
result = json.loads(response.text) # Parse JSON data using json.loads
box1_ProductToProduct = result[0]['box1_ProductToProduct'] # Extracted data from API
box2_KategorieTopseller = result[1]['box2_KategorieTopseller']
for item in box1_ProductToProduct: # loop over extracted data
print('-' * 100)
print('Brand : ',item['brand'])
print('Name : ',item['name'])
print('Net Unit Price : ',item['netUnitPrice'])
print('Product Number : ',item['product_nr'])
print('-' * 100)
for item in box2_KategorieTopseller: # loop over extracted data
print('-' * 100)
print('Brand : ',item['brand'])
print('Name : ',item['name'])
print('Net Unit Price : ',item['netUnitPrice'])
print('Product Number : ',item['product_nr'])
print('-' * 100)
scrap_product_details()
https://stackoverflow.com/questions/64571690
复制相似问题