【问题标题】:python beautifulsoup if-in-statement doesn´t work correctlypython beautifulsoup if-in-statement 不能正常工作
【发布时间】:2021-02-02 16:12:48
【问题描述】:

我对下面的网络抓取代码有疑问。该代码有效,但如果输入的产品不仅仅是一个单词,并且还包含例如“Playstation 4”之类的数字,它就会失败。问题似乎出在这一行if product in str(product_name):

我尝试了许多不同的变体,例如 product_name.textproduct_name.string,但它无法正确检查字符串 product 是否在转换后的对象 product_name 中,如果它不只是一个单词。

如果我使用print(product_name.text),我得到的结果正是我所期望的,但为什么我不能在product_name.textstr(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)

【问题讨论】:

  • 请为失败的测试添加productproduct_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


【解决方案1】:

Why should I use urlencode?

我尝试了许多不同的变体,例如 product_name.text 或 product_name.string, 但它不会正确检查字符串产品是否在转换后的对象产品名称中...

不只是一个字

URL = "http://www.somewebsite.com/search?sSearch=" + product

请查看使用连接时查询字符串会发生什么:


所以请考虑更新您的代码,如下所示:

【讨论】:

  • 我从头开始编写新代码并进行了更改。现在它似乎工作了。谢谢 :)
猜你喜欢
  • 2017-08-06
  • 1970-01-01
  • 2011-03-14
  • 1970-01-01
  • 2017-11-25
  • 1970-01-01
  • 2020-11-18
  • 2022-11-17
  • 1970-01-01
相关资源
最近更新 更多