【发布时间】:2021-02-02 16:12:48
【问题描述】:
我对下面的网络抓取代码有疑问。该代码有效,但如果输入的产品不仅仅是一个单词,并且还包含例如“Playstation 4”之类的数字,它就会失败。问题似乎出在这一行if product in str(product_name):
我尝试了许多不同的变体,例如 product_name.text 或 product_name.string,但它无法正确检查字符串 product 是否在转换后的对象 product_name 中,如果它不只是一个单词。
如果我使用print(product_name.text),我得到的结果正是我所期望的,但为什么我不能在product_name.text 或str(product_name) 中正确使用if-in-statement?
import requests
from bs4 import BeautifulSoup
product = input("Please enter product: ")
URL = "http://www.somewebsite.com/search?sSearch=" + product
website = requests.get(URL)
html = BeautifulSoup(website.text, 'html.parser')
product_info = html.find_all('div', class_="product--main")
product_array = []
for product_details in product_info:
product_name = product_details.find('a', class_="product--title product--title-desktop")
if product in str(product_name):
product_array.append(product_name.text.replace('\n', '')+'; ')
discounted_price = product_details.find('span', class_="price--default is--discount")
if discounted_price:
product_array.append(discounted_price.text.replace('\n', '').replace('\xa0€*','').replace('from','') + ';\n')
else:
regular_price = product_details.find('span', class_="price--default")
product_array.append(regular_price.text.replace('\n', '').replace('\xa0€*','').replace('from','') + ';\n' if regular_price else 'N/A;\n')
with open("data.csv", "w") as text_file:
text_file.write("product; price;\n")
for object in product_array:
text_file.write(object)
【问题讨论】:
-
请为失败的测试添加
product和product_name的值 -
检查类型(产品名称)然后你会看到。您可以使用或不使用iin
-
尝试删除代码以将其缩小到minimal reproducible example。
-
另外,如果有空格可能会切换到 if re.match(.....): 相反,因为肯定会在模式匹配中允许单词之间有空格
-
感谢所有答案...例如
product的值是"Playstation 4"和product_name的值是像<div>Playstation 4</div>和<div>Playstation 5</div>这样的抓取产品名称,我想要整理 Playstation 5 结果。使用type(product_name)返回<class 'bs4.element.Tag'>。你对 iin 是什么意思?我在if product in str(product_name):之后删除了所有代码并用简单的打印替换它以找出我的错误,但我不明白为什么它在字符串对话后不起作用。谢谢你的提示,我会用re.match试试。
标签: python beautifulsoup