使用bs4的select方法代替find_all方法,同时将css选择器的语法稍作改动。
例如,原本的代码是:
from bs4 import BeautifulSoup
html = 'This is the content.'
soup = BeautifulSoup(html, 'html.parser')
content = soup.find_all('div', class_='content')
print(content)
这里使用class作为CSS选择器,在class后面加一个下划线以避免关键字冲突。
改写后的代码如下:
from bs4 import BeautifulSoup
html = 'This is the content.'
soup = BeautifulSoup(html, 'html.parser')
content = soup.select('div.content')
print(content)
这里使用select方法以CSS选择器的形式查找class为content的div元素。值得注意的是,select方法返回的结果是一个列表,即使只有一个匹配元素也需要使用索引操作获取。