如何解决为什么要获取HTML content.txt为空?
该程序的目标很容易获得tageschau.de的标题。 一开始它很正常,但是经过几次运行却什么也没得到。
import requests
from bs4 import BeautifulSoup
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
'AppleWebKit/537.36 (KHTML,like Gecko)'
'Chrome/86.0.4240.111 Safari/537.36','Host': 'www.tagesschau.de','Referer': 'https://www.tagesschau.de/'
}
# get and parse the HTML of tageschau.de
URL = 'https://www.tagesschau.de/'
html = requests.get(URL,headers=headers)
html_parse = BeautifulSoup(html.content,'lxml')
# find all headline in homepage
elements = html_parse.find_all('h4',{'class':'headline'})
for element in elements:
print(element.txt)
一无所有。
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
但是当我使用element
而不是element.txt
时,会有一些正确的输出结果
<h4 class="headline"><a href="/multimedia/livestreams/livestream3/">Live: tagesschau24</a></h4>
<h4 class="headline"><a href="/100sekunden/">100 Sekunden</a></h4>
<h4 class="headline"><a href="/multimedia/sendung/ts-39833.html">tagesschau 20 Uhr</a></h4>
<h4 class="headline"><a href="/multimedia/sendung/ts-39841.html">Letzte Sendung</a></h4>
<h4 class="headline">++ Fauci warnt vor "einer Menge Leid" ++</h4>
<h4 class="headline">Weniger Party,mehr Wellness</h4>
<h4 class="headline">November-Lockdown kostet 19 Milliarden</h4>
这让我很困惑,为什么????
解决方法
如果要获取元素的内部文本,请尝试.text
:
for element in elements:
print(element.text)
对于innerHTML,请使用.html
:
for element in elements:
print(element.html)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。