Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Beautifulsoup将一个单元格的内容刮到另一个单元格旁边_Python_Web Scraping_Beautifulsoup_Wikipedia - Fatal编程技术网

Python Beautifulsoup将一个单元格的内容刮到另一个单元格旁边

Python Beautifulsoup将一个单元格的内容刮到另一个单元格旁边,python,web-scraping,beautifulsoup,wikipedia,Python,Web Scraping,Beautifulsoup,Wikipedia,我试图从另一个我知道其名称的单元格之外的单元格中刮取内容,例如Statsform、Amtssprache、Postleitzahl等。在图片中,所需内容始终位于正确的单元格中 基本代码如下所示,但我仍坚持使用它: source_code = requests.get('https://de.wikipedia.org/wiki/Hamburg') plain_text = source_code.text soup = BeautifulSoup(p

我试图从另一个我知道其名称的单元格之外的单元格中刮取内容,例如Statsform、Amtssprache、Postleitzahl等。在图片中,所需内容始终位于正确的单元格中

基本代码如下所示,但我仍坚持使用它:

source_code = requests.get('https://de.wikipedia.org/wiki/Hamburg')
plain_text = source_code.text                       
soup = BeautifulSoup(plain_text, "html.parser")     
stastaform = soup.find(text="Staatsform:")...???

非常感谢

这在大多数情况下都有效:

def get_content_from_right_column_for_left_column_containing(text):
    """return the text contents of the cell adjoining a cell that contains `text`"""

    navigable_strings = soup.find_all(text=text)

    if len(navigable_strings) > 1:
        raise Exception('more than one element with that text!')

    if len(navigable_strings) == 0:

        # left-column contents that are links don't have a colon in their text content...
        if ":" in text:
            altered_text = text.replace(':', '')

        # but `td`s and `th`s do.
        else: 
            altered_text = text + ":"

        navigable_strings = soup.find_all(text=altered_text)

    try:
        return navigable_strings[0].find_parent('td').find_next('td').text
    except IndexError:
        raise IndexError('there are no elements containing that text.')

我想谨慎地将搜索限制在英语维基百科中所谓的“信息箱”中。因此,我首先搜索标题“Basisdaten”,要求它是th元素。也许不完全确定,但更有可能确定。发现之后,我在“Basisdaten”下查找tr元素,直到找到另一个包含假定的不同标题的tr。在本例中,我搜索“Postleitzahlen:”但这种方法可以找到“Basisdaten”和下一个标题之间的任何/所有项目

PS:如果不是最新的,我还应该提到原因。我注意到有些行只包含新行,而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

请包含描述两个感兴趣单元格的HTML片段。是否只需要单元格中的文本或其他内容?如果我使用BeautifulSoup.get_text删除HTML脚本等,这似乎对我有效。但我在该网站上遇到了一个错误:https://de.wikipedia.org/wiki/Bremen. 你知道它是什么吗?我刚刚查看了Bearbeiten视图中两个页面的wiki代码。它们采用完全不同的方法格式化页面,因此HTML是不同的。除了高中,我没有德语。我现在明白了,不莱梅的页面上有一个“信息箱”,但汉堡的页面上没有。这与英语维基百科中的情况相同。如果你想刮它,那么你需要能够识别什么类型的格式,你正在处理和处理相应的。
<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>