我尝试使用beautifulsoup4来删除python中HTML代码的URL,但是我得到了如下错误:AttributeError:'NoneType'对象没有属性'get'
HTML代码:
<a class="top NQHJEb dfhHve" href="https://globalnews.ca/news/5137005/donald-trump-robert-mueller-report/" ping="/url?sa=t&source=web&rct=j&url=https://globalnews.ca/news/5137005/donald-trump-robert-mueller-report/&ved=0ahUKEwiS9pn-4rzhAhWOyIMKHSOPD6QQvIgBCDcwAg"><img class="th BbeB2d" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ_Nf-kVlqsQz8NeNgQ9a9YRiA7Fl4DJ6Jod0sxNXapOK_iJebx20dgROk5YBl8IqFQX6S-eeY2" alt="Story image for trump from Globalnews.ca" onload="typeof google==='object'&&google.aft&&google.aft(this)" data-iml="1554598687532" data-atf="3"></a>
我的python代码:
URL_results = soup.find_all('a', class_= 'top NQHJEb dfhHve').get('href')
您正在将该方法应用于列表。相反,您想要应用于每个元素
URL_results = [a.attrs.get('href') for a in soup.find_all('a', class_= 'top NQHJEb dfhHve')]
我更喜欢
URL_results = [item['href'] for item in soup.select('a.top.NQHJEb.dfhHve')]
并且您可以从当前的复合类选择器中删除一些类,例如
URL_results = [item['href'] for item in soup.select('a.dfhHve')]
你需要四处游玩才能看到。