beauthulsoup Python脚本不再用于挖掘简单字段

2024-05-29 11:05:06 发布

您现在位置:Python中文网/ 问答频道 /正文

这个剧本以前有用,但现在不行了,我不知道为什么。我正在尝试转到链接并提取/打印宗教字段。使用firebug,宗教字段条目位于“tbody”然后是“td”标记结构中。但是现在脚本在搜索这些标记时会找到“none”。我也看了一下lxml的“print Soup_FamSearch”,我没看到firebug上出现任何“tbody”和“td”标签。在

请告诉我我缺少什么?在

import urllib2
import re
import csv
from bs4 import BeautifulSoup
import time
from unicodedata import normalize

FamSearchURL = 'https://familysearch.org/pal:/MM9.1.1/KH21-211'
OpenFamSearchURL = urllib2.urlopen(FamSearchURL)
Soup_FamSearch = BeautifulSoup(OpenFamSearchURL, 'lxml')
OpenFamSearchURL.close()

tbodyTags = Soup_FamSearch.find('tbody')
trTags = tbodyTags.find_all('tr', class_='result-item ')

for trTags in trTags:
    tdTags_label = trTag.find('td', class_='result-label ')
    if tdTags_label:
        tdTags_label_string = tdTags_label.get_text(strip=True)

        if tdTags_label_string == 'Religion: ':
            print trTags.find('td', class_='result-value ')

Tags: 标记importresultfindlabelclasstdsoup
1条回答
网友
1楼 · 发布于 2024-05-29 11:05:06

找到Religion:标签by text,得到next ^{} sibling

soup.find(text='Religion:').parent.find_next_sibling('td').get_text(strip=True)

演示:

^{pr2}$

然后,您可以创建一个很好的可重用函数并重用:

def get_field_value(soup, field):
    return soup.find(text='%s:' % field).parent.find_next_sibling('td').get_text(strip=True)

print get_field_value(soup, 'Religion')
print get_field_value(soup, 'Nationality')
print get_field_value(soup, 'Birthplace')

印刷品:

Methodist
Canadian
Ontario

相关问题 更多 >

    热门问题