python - 如何抓取具有相同模式的不同类名

标签 python beautifulsoup

我正在尝试从网页中抓取数据。然而,类名并不完全相同,但遵循相似的模式。类名如下

View 行 View -行-1 View -行-奇数clearfix

View 行 View -行-2 View 行-甚至clearfix

View 行 View -行3 View -行奇数clearfix

我尝试了下面的代码,但没有成功!可能是我使用的语法错误。

from bs4 import BeautifulSoup
import requests
source = requests.get('http://news.mit.edu/topic/artificial-intelligence2').text
soup = BeautifulSoup(source, 'lxml')
match = soup.find_all('li', class_='views-row views-row-* views-row-* clearfix')
print(match)

请帮我解决这个问题。

最佳答案

regex 过滤类值表达式:

from bs4 import BeautifulSoup
import requests

source = requests.get('http://news.mit.edu/topic/artificial-intelligence2').content
soup = BeautifulSoup(source, 'html.parser')

li_tags = soup.find_all('li', class_= re.compile(r'views-row views-row-[0-9]+ views-row-(odd|even) clearfix'))
print(li_tags)
<小时/>

为了更简化的搜索,您可以将 soup.select 与 css 选择器一起应用:

li_tags = soup.select('li[class*=views-row-]')
print(li_tags)

关于python - 如何抓取具有相同模式的不同类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57614788/

相关文章:

python - 我如何在不重复计算的情况下计算 python 中数据框的所有唯一值?

python - 可以在 Python 中使用 BeautifulSoup 或正则表达式解析此半结构化文本文件

python - 将 beautifulsoup 中的 findall() 限制为 html 的一部分

python - 类型错误 : 'list' object is not callable when web scraping to append lists/values to a column in csv file

python-beautifulsoup 误报了我的 html 吗?

python - 如何在字符串中搜索单词并根据匹配的大小写进行不同的打印?

python - 拆分字符串并生成键值对

python - 如何将数据框变成一系列列表?

java - Jython jlist 文本未显示在 JFrame 中

python - 选择 sibling ,但中间没有任何东西