我想在限制搜索到什么是所谓的英文维基百科的“信息框”必须小心。因此,我首先搜索标题'Basisdaten',要求它是一个th
元素。可能并不完全确定,但可能性更大。发现我在'Basisdaten'下查找tr
元素,直到我找到另一个tr
,包括一个(推测不同的)标题。在这种情况下,我搜索'Postleitzahlen:',但是这种方法可以找到'Basisdaten'和下一个标题之间的任何/所有项目。
PS:我还应该提一下if not current.name
的原因。我注意到一些行由BeautifulSoup视为字符串的新行组成。这些没有名称,因此需要在代码中专门对待它们。
import requests
import bs4
page = requests.get('https://de.wikipedia.org/wiki/Hamburg').text
soup = bs4.BeautifulSoup(page, 'lxml')
def getInfoBoxBasisDaten(s):
return str(s) == 'Basisdaten' and s.parent.name == 'th'
basisdaten = soup.find_all(string=getInfoBoxBasisDaten)[0]
wanted = 'Postleitzahlen:'
current = basisdaten.parent.parent.nextSibling
while True:
if not current.name:
current = current.nextSibling
continue
if wanted in current.text:
items = current.findAll('td')
print (items[0])
print (items[1])
if '<th ' in str(current): break
current = current.nextSibling
结果是这样的:两个单独的td
元素,请求。
<td><a href="/wiki/Postleitzahl_(Deutschland)" title="Postleitzahl (Deutschland)">Postleitzahlen</a>:</td>
<td>20095–21149,<br/>
22041–22769,<br/>
<a href="/wiki/Neuwerk_(Insel)" title="Neuwerk (Insel)">27499</a></td>
请包括描述两个感兴趣的单元格的HTML片段。 – DyZ
你只想要单元格中的文本,还是更多? –