【发布时间】:2014-12-09 18:03:20
【问题描述】:
看着US Census QFD,我正试图按县抢占比赛百分比。我正在构建的循环超出了我的问题范围,这与此代码有关:
url = 'http://quickfacts.census.gov/qfd/states/48/48507.html'
#last county in TX; for some reason the qfd #'s counties w/ only odd numbers
page = urllib2.urlopen(url)
soup = BeautifulSoup(page)
c_black_alone = soup.find_all("td", attrs={'headers':'rp9'})[0] #c = county %
s_black_alone = soup.find_all("td", attrs={'headers':'rp9'})[1] #s = state %
它抓取 html 元素,包括其标签,而不仅仅是其中的文本:
c_black_alone, s_black_alone
(<td align="right" headers="rp9 p1" valign="bottom">96.9%<sup></sup></td>,
<td align="right" headers="rp9 p2" valign="bottom">80.3%<sup></sup></td>)
在 ^ 上面,我只想要元素内的 %...
还有,为什么
test_black = soup.find_all("td", text = "Black")
不返回与上面相同的元素(或其文本),而是返回一个空的 bs4 ResultSet 对象? (编辑:我一直在关注文档,所以我希望这个问题看起来不会太模糊......)
【问题讨论】:
-
您为什么希望第二个
find_all()返回第一个元素?这些元素中没有直接包含此类文本。除非您使用正则表达式,否则第二次搜索不会匹配任何内容。 -
@MartijnPieters 我实际上也尝试过
test_black = soup.find_all("td", text = re.compile("Black")),它也返回一个空的ResultSet obj。我的印象是,因为文本出现在父元素中,所以它会找到(_all)那个元素并返回它...... -
我在这里误解了什么吗? bs4: text argument
-
文字字符串值只匹配全部内容,而不是部分匹配。
标签: python html web-scraping beautifulsoup