通常情况下,BeautifulSoup.select可以通过使用CSS选择器来查找元素。如果classname无法正常工作,可以尝试以下方法解决:
1.使用BeautifulSoup.select_one方法代替BeautifulSoup.select方法。这可以返回第一个匹配的元素,而不是匹配的元素列表。例如:
from bs4 import BeautifulSoup
soup = BeautifulSoup("Hello World!", "html.parser")
result = soup.select_one('.example')
print(result.text)
输出:
Hello World!
2.对于无法使用点号来选择classname的特殊情况,可以使用BeautifulSoup.find_all方法和正则表达式来查找元素。例如:
import re
from bs4 import BeautifulSoup
soup = BeautifulSoup("Hello World!Goodbye World!", "html.parser")
results = soup.find_all('div', class_=re.compile(r'^example-\d$'))
for result in results:
print(result.text)
输出:
Hello World!