【问题标题】:Unable to Scrape Content that comes after a Comment Python BeautifulSoup无法抓取评论后出现的内容 Python BeautifulSoup
【发布时间】:2018-07-29 02:47:31
【问题描述】:

我正在尝试从以下页面抓取表格:

https://www.baseball-reference.com/boxes/CHA/CHA193805220.shtml

当我到达击球台的 html 时,我遇到了一个很长的评论,其中包含该表的 html

<div id="all_WashingtonSenatorsbatting" class="table_wrapper table_controls">
     <div class="section_heading">
     <div class="section_heading_text">
     <div class="placeholder"></div>
     <!-- 
        <div class="table_outer_container">
        .....
        -->
     <div class="table_outer_container mobile_table">
     <div class="footer no_hide_long">

最后两个div 是我感兴趣的内容,而&lt;!----&gt; 之间的所有内容都是注释,其中恰好包含下面table_outer_container 类中的表格副本。

问题是当我将页面源读入漂亮的汤时,它不会在包含所有内容的table_wrapperdiv 中的评论之后读取任何内容。下面的代码说明了这个问题:

batting = page_source.find('div', {'id':'all_WashingtonSenatorsbatting'})
divs = batting.find_all('div')
len(divs)

给我

Out[1]: 3

div id="all_WashingtonSenatorsbatting"元素下明显有5个div子元素时。

即使我使用

提取评论
from bs4 import Comment
for comments in soup.findAll(text=lambda text:isinstance(text, Comment)):
     comments.extract()

生成的汤仍然不包含我要抓取的最后两个 div 元素。我正在尝试使用正则表达式来处理代码,但到目前为止还没有运气,有什么建议吗?

【问题讨论】:

    标签: python html web-scraping beautifulsoup comments


    【解决方案1】:

    我找到了可行的解决方案,通过使用以下代码,我提取了注释(它带来了我想要抓取的最后两个 div 元素),在 BeautifulSoup 中再次处理并抓取表格

    s = requests.get(url).content
    soup = BeautifulSoup(s, "html.parser")
    table = soup.find_all('div', {'class':'table_wrapper'})[0]
    comment = t(text=lambda x: isinstance(x, Comment))[0]
    newsoup = BeautifulSoup(comment, 'html.parser')
    table = newsoup.find('table')
    

    我花了一段时间才解决这个问题,并且有兴趣看看是否有人提出任何其他解决方案或可以解释这个问题是如何产生的。

    【讨论】:

      猜你喜欢
      • 2019-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-17
      • 1970-01-01
      • 2022-08-18
      相关资源
      最近更新 更多