如何用Python从HTML中提取它?

时间:2014-09-25 00:09:29

标签: python html html-parsing beautifulsoup mechanize

我正在尝试提取该数据:

<div class="address"><h3>Text1</h3><div class="adr">Text2</div></div>

我想打印text1和text2。

我试试这个:

br = mechanize.Browser()
html = """<div class="address"><h3></h3><div class="adr"></div></div>"""
soup = BeautifulSoup(html)
br.addheaders = [('User-agent', 'Firefox')]
br.open("http://de.fakenamegenerator.com/gen-male-gr-gr.php")
adress = soup.findAll('div', attrs={ "class" : "adr"})

print len(adress)

我得到结果:

1

...

谢谢!

1 个答案:

答案 0 :(得分:1)

首先,您需要使用mechanize发出请求,然后将response传递给BeautifulSoup进行解析:

from bs4 import BeautifulSoup
import mechanize

br = mechanize.Browser()
br.addheaders = [('User-agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.122 Safari/537.36')]
br.open("http://de.fakenamegenerator.com/gen-male-gr-gr.php")

soup = BeautifulSoup(br.response())
address = soup.find('div', attrs={"class": "address"})

print address.h3.text.strip()
print address.find('div', attrs={'class': 'adr'}).text.strip()

打印:

Jan Amsel
Invalidenstrasse 6567159 Friedelsheim