【问题标题】:Search for words in hyperlink Python 3在超链接 Python 3 中搜索单词
【发布时间】:2020-09-21 19:42:20
【问题描述】:

我正在编写一个 python 3 脚本来抓取网站并检查产品是否有库存。我遇到的问题是在我从 BeautifulSoup 获取的超链接中搜索产品名称。产品名称会有一个空格,所以它实际上是 2 个单词,我认为这就是导致问题的原因。

** product_name 传入,例如:“Blue Truck” 示例链接:<a href="https://example.com/products/">Blue Truck</a>

soup = BeautifulSoup(driver.page_source, 'html.parser')
print("Trying to find links " + threadName)
for a in soup.findAll('a'):
     if product_name in a['href']:
        email_link(a)
        print("FOUND" + threadName)
        break
     elif product_name.lower() in a['href']:
        email_link(a)
        print("FOUND" + threadName)
        break
     

运行此代码时,它永远不会返回匹配项。我也试过了:

 if (a.find(product_name) != -1):
    email_link(a)

此 find() 返回错误匹配项。任何帮助都会很好,或者建议哪种方式最快。

【问题讨论】:

  • 试试 a.text 而不是 a['href']

标签: python beautifulsoup


【解决方案1】:

a 标签"<a href="https://example.com/products/">Blue Truck</a> 具有以下属性:

  • href: "https://example.com/products/"
  • innerHTMLtext:蓝色卡车

代码正在寻找a['href'],即"https://example.com/products/"。您要查找a.text,即Blue Truck

【讨论】:

    【解决方案2】:

    您应该实现以下内容:

    import bs4 as bs
    import urllib.parse
    
    soup = bs.BeautifulSoup(driver.page_source, 'html.parser')
    print("Trying to find link for " + thread_name)
    for a in soup.find_all('a'):
        if (product_name.lower() in a.text.lower()) or (urllib.parse.quote(product_name.lower()) in a['href']): # can also add regex
            email_link(a)
            print("FOUND" + thread_name)
            break
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-05
      • 1970-01-01
      • 1970-01-01
      • 2021-09-02
      • 2015-09-15
      • 2019-11-26
      • 2014-12-23
      • 1970-01-01
      相关资源
      最近更新 更多