使用BeautifulSoup从div中的p提取文本 [英] Extract the text from `p` within `div` with BeautifulSoup

查看:415
本文介绍了使用BeautifulSoup从div中的p提取文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对使用Python进行网络爬虫非常陌生,并且在从HTML(准确地说是div中的p)提取嵌套文本方面确实很难.这是到目前为止我得到的:

I am very new to web-scraping with Python, and I am really having a hard time with extracting nested text from within HTML (p within div, to be exact). Here is what I got so far:

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中的文本.这是我使用的代码:

Now, I want to extract the text within p and /p. This is the code I use:

table = soup.findAll('div',attrs={"class":"content-question"})
for x in table:
    print(x['p'])

但是,Python会引发KeyError.

However, Python raises a KeyError.

推荐答案

以下代码使用class"content-question"查找并打印div中每个p元素的文本

The following code finds and prints the text of each p element in the div's with the class "content-question"

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"]')

以下是table中第一个p元素的打印文本:

The following is the printed text of the first p element in table:

[...]死于法治的维斯塔贝根州立大学纪念馆,苏克塔斯·尼采·谢赫海特·格塞格特·沃登·坎登,瑞士的维萨·卢布·德·维希德·弗朗西斯·维斯塔布吕格一般情况下,本人可享有任何权利.因此,Drins Visaerleichterungenbzw. -liberalisierungen eine Frage vonReziprozitätsind,d.h. Staaten geltenmüssten. [...]

[...] Die Verhandlungen über die mögliche Visabefreiung für türkische Staatsbürger per Ende Juni sind noch nicht abgeschlossen, sodass nicht mit Sicherheit gesagt werden kann, ob es zu diesem Zeitpunkt bereits zu einer Visabefreiung kommt. Auch die genauen Modalitäten einer solchen Visaliberalisierung sind noch nicht ausverhandelt. Prinzipiell ist es jedoch so, dass Visaerleichterungen bzw. -liberalisierungen eine Frage von Reziprozität sind, d.h. dass diese für beide Staaten gelten müssten. [...]

这篇关于使用BeautifulSoup从div中的p提取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆