我正在从中提取内容url https://www.collinsdictionary.com/dictionary/french-english/aimer.
import requests
from bs4 import BeautifulSoup
url = 'https://www.collinsdictionary.com/dictionary/french-english/aimer'
headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0'}
soup = BeautifulSoup(requests.get(url, headers = headers).content, 'html.parser')
for script in soup.select('script, .hcdcrt, #ad_contentslot_1, #ad_contentslot_2'):
script.extract()
entry_name = soup.h2.text
content1 = ''.join(map(str, soup.select_one('.cB cB-def dictionary biling').contents))
然后我得到一个错误
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-84-e9cb11cd6b5d> in <module>
10
11 entry_name = soup.h2.text
---> 12 content1 = ''.join(map(str, soup.select_one('.cB cB-def dictionary biling').contents))
AttributeError: 'NoneType' object has no attribute 'contents'
另一方面,如果我替换cB cB-def dictionary biling
by hom
, i.e. content1 = ''.join(map(str, soup.select_one('.hom').contents))
然后代码运行良好。从下面的html结构来看,我认为cB cB-def dictionary biling
and hom
非常相似。
您能详细说明一下这个问题是如何产生的以及如何解决吗?