Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.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
BeautifulSoup Python脚本不再用于挖掘简单字段_Python_Python 2.7_Web Scraping_Beautifulsoup_Html Parsing - Fatal编程技术网

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

BeautifulSoup Python脚本不再用于挖掘简单字段,python,python-2.7,web-scraping,beautifulsoup,html-parsing,Python,Python 2.7,Web Scraping,Beautifulsoup,Html Parsing,这个剧本过去很管用,但现在不管用了,我不明白为什么。我正在尝试转到链接并提取/打印宗教字段。使用firebug,宗教字段条目位于“tbody”然后是“td”标记结构中。但是现在脚本在搜索这些标记时会找到“none”。我还通过“print Soup_FamSearch”查看了lxml,我没有看到firebug上出现任何“tbody”和“td”标签 请让我知道我错过了什么 import urllib2 import re import csv from bs4 import BeautifulSou

这个剧本过去很管用,但现在不管用了,我不明白为什么。我正在尝试转到链接并提取/打印宗教字段。使用firebug,宗教字段条目位于“tbody”然后是“td”标记结构中。但是现在脚本在搜索这些标记时会找到“none”。我还通过“print Soup_FamSearch”查看了lxml,我没有看到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 ')

找到
宗教:
标签并获取:

演示:


然后,您可以制作一个很好的可重用函数并进行重用:

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

我从来都不知道这种找到标签的好方法,谢谢。不过,当我尝试演示代码时,我得到了这个“AttributeError:“NoneType”对象没有属性“parent”,这也是我从原始程序中得到的。@KubiK888谢谢,您确定已安装
lxml
?(如果未安装
lxml
,我可以重现错误,获取
bs4.FeatureNotFound:找不到具有您请求的功能的树生成器:lxml。是否需要安装解析器库?
在控制台上,然后
AttributeError:'NoneType'对象没有属性'parent'
错误)您是对的。但这有点有趣和奇怪。我通过重新运行“pip install lxml”来确保我已经安装了lxml模块,安装过程似乎正常,但脚本给出了相同的错误。只有从下载并安装lxml模块,它才能正常工作。谢谢
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