使用BeautifulSoup从div中的`p`中提取文本
我非常新的网页抓取与Python,和我真的有一个很难用HTML内从提取嵌套文本(p
中div
,要准确)。这是到目前为止我得到的:
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
。
-
以下代码使用“ content-question” 查找并打印的每个
p
元素的文本div``class
from bs4 import BeautifulSoup import urllib url = urllib.urlopen('http://meinparlament.diepresse.com/') content = url.read() soup = BeautifulSoup(content, 'lxml') table = soup.findAll('div',attrs={"class":"content-question"}) for x in table: print x.find('p').text # Another way to retrieve tables: # table = soup.select('div[class="content-question"]')
以下是中第一个
p
元素的印刷文本table
:[…]关于截至6月底可能对土耳其公民免签证的谈判尚未结束,因此无法确定地说是否将在此时准予免签证。此类签证自由化的确切方式也尚未谈判。但是,原则上签证便利化或自由化是互惠的问题,也就是说,这应适用于两个国家。[…]