BeautifulSoup 的 "find" 行为不一致 (bs4)
BeautifulSoup's "find" acting inconsistently (bs4)
我正在抓取 NFL 的网站以获取球员统计信息。我在解析网页并尝试访问包含我要查找的实际信息的 HTML table 时遇到问题。我成功下载了该页面并将其保存到我正在工作的目录中。作为参考,可以找到我保存的页面here。
# import relevant libraries
import pandas as pd
import numpy as np
from bs4 import BeautifulSoup
soup = BeautifulSoup(open("1998.html"))
result = soup.find(id="result")
print result
我发现我 运行 代码和结果打印了我正在寻找的正确 table。每隔一段时间,它什么都不包含!我假设这是用户错误,但我不知道我错过了什么。使用 "lxml" 没有返回任何结果,我无法让 html5lib 工作(解析库??)。
感谢任何帮助!
首先,您应该在将文件传递给 BeautifulSoup 之前阅读文件内容。
soup = BeautifulSoup(open("1998.html").read())
其次,通过将内容打印到屏幕,手动验证 HTML 中是否存在有问题的 table
。 .prettify()
方法使数据更易于阅读。
print soup.prettify()
最后,如果该元素确实存在,以下将能够找到它:
table = soup.find('table',{'id':'result'})
我写的一个简单的测试脚本无法重现你的结果。
import urllib
from bs4 import BeautifulSoup
def test():
# The URL of the page you're scraping.
url = 'http://www.nfl.com/stats/categorystats?tabSeq=0&statisticCategory=PASSING&conference=null&season=1998&seasonType=REG&d-447263-s=PASSING_YARDS&d-447263-o=2&d-447263-n=1'
# Make a request to the URL.
conn = urllib.urlopen(url)
# Read the contents of the response
html = conn.read()
# Close the connection.
conn.close()
# Create a BeautifulSoup object and find the table.
soup = BeautifulSoup(html)
table = soup.find('table',{'id':'result'})
# Find all rows in the table.
trs = table.findAll('tr')
# Print to screen the number of rows found in the table.
print len(trs)
每次输出51
。
我正在抓取 NFL 的网站以获取球员统计信息。我在解析网页并尝试访问包含我要查找的实际信息的 HTML table 时遇到问题。我成功下载了该页面并将其保存到我正在工作的目录中。作为参考,可以找到我保存的页面here。
# import relevant libraries
import pandas as pd
import numpy as np
from bs4 import BeautifulSoup
soup = BeautifulSoup(open("1998.html"))
result = soup.find(id="result")
print result
我发现我 运行 代码和结果打印了我正在寻找的正确 table。每隔一段时间,它什么都不包含!我假设这是用户错误,但我不知道我错过了什么。使用 "lxml" 没有返回任何结果,我无法让 html5lib 工作(解析库??)。
感谢任何帮助!
首先,您应该在将文件传递给 BeautifulSoup 之前阅读文件内容。
soup = BeautifulSoup(open("1998.html").read())
其次,通过将内容打印到屏幕,手动验证 HTML 中是否存在有问题的 table
。 .prettify()
方法使数据更易于阅读。
print soup.prettify()
最后,如果该元素确实存在,以下将能够找到它:
table = soup.find('table',{'id':'result'})
我写的一个简单的测试脚本无法重现你的结果。
import urllib
from bs4 import BeautifulSoup
def test():
# The URL of the page you're scraping.
url = 'http://www.nfl.com/stats/categorystats?tabSeq=0&statisticCategory=PASSING&conference=null&season=1998&seasonType=REG&d-447263-s=PASSING_YARDS&d-447263-o=2&d-447263-n=1'
# Make a request to the URL.
conn = urllib.urlopen(url)
# Read the contents of the response
html = conn.read()
# Close the connection.
conn.close()
# Create a BeautifulSoup object and find the table.
soup = BeautifulSoup(html)
table = soup.find('table',{'id':'result'})
# Find all rows in the table.
trs = table.findAll('tr')
# Print to screen the number of rows found in the table.
print len(trs)
每次输出51
。