【问题标题】:Can't get beautiful soup to work with my callback function and regex无法让漂亮的汤与我的回调函数和正则表达式一起使用
【发布时间】:2021-12-13 01:57:54
【问题描述】:

所以我尝试使用以下代码从 href 属性与模式 /how-to-use/[a-zA-Z]+ 匹配的网站中抓取所有标签

代码在这里:

import requests
from bs4 import BeautifulSoup
import re

webpage = requests.get('https://www.talkenglish.com/vocabulary/top-1500-nouns.aspx').content
soup = BeautifulSoup(webpage, "html.parser")

def has_how_to_use(tag):
    pattern = re.compile('\/how-to-use\/[a-zA-Z]+')
    return bool(re.search(pattern, tag.attr('href')))

word_list = soup.find_all(has_how_to_use)

但我不断收到关于无法调用 NoneType 对象的错误,我只是不确定哪个位正在评估为 NoneType 对象

【问题讨论】:

    标签: python regex web-scraping beautifulsoup


    【解决方案1】:

    您可以将您的正则表达式模式作为关键字参数传递给find_all(),以查找所有包含您的模式的href

    soup = BeautifulSoup(webpage, "html.parser")
    
    for tag in soup.find_all("a", href=re.compile(r"/how-to-use/[a-zA-Z]+")):
        print(tag)
    

    【讨论】:

      猜你喜欢
      • 2020-03-17
      • 2012-10-12
      • 2017-06-05
      • 2017-11-14
      • 2017-01-15
      • 2017-12-14
      • 1970-01-01
      • 1970-01-01
      • 2017-04-27
      相关资源
      最近更新 更多