BeautifulSoup find_all 方法没有泛化

Posted

技术标签:

【中文标题】BeautifulSoup find_all 方法没有泛化【英文标题】:BeautifulSoup find_all Method not Generalising 【发布时间】:2021-08-17 17:44:17 【问题描述】:

我有点纠结于 BeautifulSoup 的问题。这段代码是我正在尝试调试的函数的 sn-p。刮刀工作正常,突然停了下来。奇怪的是,我正在搜索“ipsColumn ipsColumn_fluid”的类在循环的第二步生成的“post_soup”文件中。

作为调试的一部分,我想看看生成了什么是文本文件的原因。然而,它是空的。我不知道为什么。

有什么想法吗?

post_pages = ['https://coffeeforums.co.uk/topic/4843-a-little-thank-you/', 'https://coffeeforums.co.uk/topic/58690-for-sale-area-rules-changes-important/']

for topic_url in post_pages:
    post_page = urlopen(topic_url)
    post_soup = BeautifulSoup(post_page, 'lxml')
    messy_posts = post_soup.find_all('div',  class_='ipsColumn ipsColumn_fluid')
    with open('messy_posts.txt', 'w') as f:
        f.write(str(messy_posts))

编辑:您可以交换此变量以查看它应该如何工作。这些网站建立在同一个平台上,所以抓取应该是相同的(我认为):

post_pages = ['https://forum.cardealermagazine.co.uk/topic/8603-customer-comms-and-the-virus/', 'https://forum.cardealermagazine.co.uk/topic/10096-volvo-issue-heads-up/']

【问题讨论】:

预期输出是什么? 尝试使用 css 选择器它会起作用,因为它找不到所需的输出空间 【参考方案1】:

class_ 接受多个类的列表,而不是 OR 操作的字符串。您可以将其更改为

 class_='ipsColumn ipsColumn_fluid'

到此为止,它应该可以工作。

class_=['ipsColumn', 'ipsColumn_fluid']

它应该可以工作。

或者,如果您要使用 AND(您想要一个包含两个类的 div)。我建议你这样使用select

post_soup.select('div.ipsColumn.ipsColumn_fluid')

这将返回包含两个类的 div

【讨论】:

这不是真的。如果 OP 想要完全匹配 html 标签的 class 属性的字符串值,class_='ipsColumn ipsColumn_fluid' 完全可以。您提议的更改 class_=['ipsColumn', 'ipsColumn_fluid'] 使用逻辑 OR 过滤器,即匹配 class='ipsColumn'class='ipsColumn_fluid'class='ipsColumn ipsColumn_fluid

以上是关于BeautifulSoup find_all 方法没有泛化的主要内容,如果未能解决你的问题,请参考以下文章

BeautifulSoup find_all 方法没有泛化

为啥使用 BeautifulSoup find_all 方法会导致错误(列表索引超出范围)?

03_BeautifulSoup的使用2-搜索文档树

BeautifulSoup 中“findAll”和“find_all”的区别

Beautiful Soup 中 find_all 方法的返回类型是啥?

BeautifulSoup 从 find_all 的结果中找到 url