【发布时间】:2016-08-12 08:08:25
【问题描述】:
我对使用 Python 进行网络抓取非常陌生,而且我真的很难从 HTML 中提取嵌套文本(确切地说是div 中的p)。这是我到目前为止得到的:
from bs4 import BeautifulSoup
import urllib
url = urllib.urlopen('http://meinparlament.diepresse.com/')
content = url.read()
soup = BeautifulSoup(content, 'lxml')
这很好用:
links=soup.findAll('a',{'title':'zur Antwort'})
for link in links:
print(link['href'])
此提取工作正常:
table = soup.findAll('div',attrs={"class":"content-question"})
for x in table:
print(x)
这是输出:
<div class="content-question">
<p>[...] Die Verhandlungen über die mögliche Visabefreiung für
türkische Staatsbürger per Ende Ju...
<a href="http://meinparlament.diepresse.com/frage/10144/" title="zur
Antwort">mehr »</a>
</p>
</div>
现在,我想提取p 和/p 中的文本。这是我使用的代码:
table = soup.findAll('div',attrs={"class":"content-question"})
for x in table:
print(x['p'])
但是,Python 会引发 KeyError。
【问题讨论】:
标签: python python-3.x web-scraping beautifulsoup