Python/Beautiful Soup – 在div中的标题内查找字符串
作为一个刚接触Python的新手,我花了大约一个小时想用Python 2.7.x和Beautiful Soup从一个div里的标题中找到一个字符串:
import urllib2
from bs4 import BeautifulSoup
request = urllib2.Request("http://somerandomurl.org")
response = urllib2.urlopen(request)
soup = BeautifulSoup(response)
这个HTML文件长这样:
<div class="ABC">
<h1>My string</h1>
</div>
我不能在这里详细描述我在Beautiful Soup文档中尝试过的所有方法(包括print soup.div('ABC').h1
……),但我想我在阅读时可能搞错了什么。谢谢大家的帮助。
1 个回答
3
你想要的是:
soup.find('div', class_='ABC').h1
这个代码会找到第一个带有 ABC
类的 div
标签,然后再找到它里面的第一个 H1 标签:
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup('''
... <div class="ABC">
... <h1>My string</h1>
... </div>
... ''')
>>> soup.find('div', class_='ABC').h1
<h1>My string</h1>