Python 3.x 使用Beautifulsoup解析大评论?

Python 3.x 使用Beautifulsoup解析大评论?,python-3.x,beautifulsoup,Python 3.x,Beautifulsoup,我正在使用BS4来解析: 您会注意到页面上有两个单独的表。下面是我的代码的相关片段,它成功地从第一个表返回了我想要的数据,但没有从第二个表中找到任何内容: # import packages import urllib3 import certifi from bs4 import BeautifulSoup import pandas as pd #settings http = urllib3.PoolManager( cert_reqs='CERT_REQUIRED',

我正在使用BS4来解析: 您会注意到页面上有两个单独的表。下面是我的代码的相关片段,它成功地从第一个表返回了我想要的数据,但没有从第二个表中找到任何内容:

# import packages
import urllib3
import certifi
from bs4 import BeautifulSoup
import pandas as pd

#settings
http = urllib3.PoolManager(
        cert_reqs='CERT_REQUIRED',
        ca_certs=certifi.where())
gamelog_offense = []

#scrape the data and write the .csv files
url = "https://www.sports-reference.com/cfb/schools/florida/2018/gamelog/"
response = http.request('GET', url)
soup = BeautifulSoup(response.data, features="html.parser")
cnt = 0

for row in soup.findAll('tr'):
    try:
        col=row.findAll('td')
        Pass_cmp = col[4].get_text()
        Pass_att = col[5].get_text()
        gamelog_offense.append([Pass_cmp, Pass_att])
        cnt += 1
    except:
        pass
print("Finished writing with " + str(cnt) + " records")
Finished writing with 13 records
我已经验证了第二个表中的数据是否包含在汤中(我可以看到!)。经过大量的故障排除,我发现整个第二个表完全包含在一个大注释中(为什么?)。我使用下面的代码成功地将此注释提取到单个注释对象中,但不知道在提取完所需数据之后如何处理它。理想情况下,我希望以与成功解析第一个表相同的方式解析注释。我尝试过使用类似堆栈溢出问题(selenium、phantomjs)中的想法…运气不好

import bs4
defense = soup.find(id="all_defense")
for item in defense.children:
    if isinstance(item, bs4.element.Comment):
        big_comment = item
print(big_comment)
<div class="table_outer_container">
  <div class="overthrow table_container" id="div_defense">
   ...and so on....
导入bs4
防御=汤。查找(id=“所有防御”)
对于defense.children中的项目:
如果isinstance(项,bs4.element.Comment):
大注释=项目
打印(大注释)
等等

在此处发布答案,以防其他人发现有帮助。非常感谢@TomasCarvalho指导我找到解决方案。我能够使用以下代码将大注释作为html传递到第二个soup实例,然后在新的soup实例上使用原始解析代码。(注意:try/except是因为一些团队没有游戏日志,您不能在非类型上调用.children

try:
    defense = soup.find(id="all_defense")
    for item in defense.children:
        if isinstance(item, bs4.element.Comment):
            html = item
    Dsoup = BeautifulSoup(html, features="html.parser")
except:
    html = ''
    Dsoup = BeautifulSoup(html, features="html.parser")

你有一个要解析的字符串吗?在这种情况下,也许可以试试:太棒了……这非常有帮助,解决了问题!我能够将注释作为html传递到第二个soup实例中并进行解析。谢谢!(这是我第一次发布问题……如果你发表评论而不是回答,我如何“奖励”你的帮助?(即,对评论进行投票?)如果你有足够的声誉,你可以对我的评论进行投票。我发表评论是因为我没有提供答案,而是指向可能的解决方案:)很高兴我能提供帮助!