这个问题可能非常具体。我试图从https://en.wikipedia.org/wiki/3M等公司的维基百科页面中提取员工人数。
我尝试使用Wikipedia python API和一些正则表达式查询。但是,我找不到任何可以为任何公司推广的实体(不考虑例外)。
另外,因为表行没有id或类,所以我无法直接访问该值。以下是来源:
<tr>
<th scope="row" style="padding-right:0.5em;">
<div style="padding:0.1em 0;line-height:1.2em;">Number of employees</div>
</th>
<td style="line-height:1.35em;">89,800 (2015)<sup id="cite_ref-FY_1-5" class="reference"><a href="#cite_note-FY-1">[1]</a></sup></td>
</tr>
所以,即使我有表格的ID - infobox vcard
,所以我无法找到使用beautifulSoup
来抓取此信息的方法。
有没有办法提取这些信息?它出现在页面开头右侧的摘要表中。
答案 0 :(得分:2)
使用lxml.etree
代替BeautifulSoup,您可以通过XPath表达式获得所需内容:
>>> from lxml import etree
>>> import requests
>>> r = requests.get('https://en.wikipedia.org/wiki/3M')
>>> doc = etree.fromstring(r.text)
>>> e = doc.xpath('//table[@class="infobox vcard"]/tr[th/div/text()="Number of employees"]/td')
>>> e[0].text
'89,800 (2015)'
让我们仔细看看这个表达式:
//table[@class="infobox vcard"]/tr[th/div/text()="Number of employees"]/td
那说:
查找属性
table
设置为class
的所有infobox vcard
元素,并在这些元素中查找具有tr
元素的th
元素 包含子div
元素的子tr
元素 text&#34;员工人数&#34;以及td
元素内部的人员 第一个c+geom_bar(aes(y=(..count..)/sum(..count..)*100))
元素。
答案 1 :(得分:0)