【问题标题】:Grabbing the main text content of an HTML tag without the <span> inside抓取没有 <span> 的 HTML 标记的主要文本内容
【发布时间】:2020-08-02 05:20:12
【问题描述】:

我正在构建一个 Python 网络爬虫,它通过 eBay 搜索结果页面(在本例中为“游戏笔记本电脑”)并获取每件待售商品的标题。我正在使用 BeautifulSoup 首先获取存储每个标题的 h1 标签,然后将其打印为文本:

    for item_name in soup.findAll('h1', {'class': 'it-ttl'}):
    print(item_name.text)

然而,在每个带有'it-ttl'类的h1标签中,还有一个包含一些文本的span标签:

<h1 class="it-ttl" itemprop="name" id="itemTitle">
 <span class="g-hdn">Details about  &nbsp;</span>
 Acer - Nitro 5 15.6" Gaming Laptop - Intel Core i5 - 8GB Memory - NVIDIA GeFo…
</h1>

我当前的程序打印出 span 标签 的内容标题: My console output

有人可以向我解释如何在忽略包含“详细信息”文本的跨度标签的情况下获取项目标题吗?谢谢!

【问题讨论】:

标签: python web-scraping beautifulsoup web-crawler html-parsing


【解决方案1】:

只需删除有问题的&lt;span&gt;即可:

item = """
<h1 class="it-ttl" itemprop="name" id="itemTitle">
 <span class="g-hdn">Details about  &nbsp;</span>
 Acer - Nitro 5 15.6" Gaming Laptop - Intel Core i5 - 8GB Memory - NVIDIA GeFo…
</h1>
"""
from bs4 import BeautifulSoup as bs
soup = bs(item,'lxml')
target = soup.select_one('h1')
target.select_one('span').decompose()
print(target.text.strip())

输出:

Acer - Nitro 5 15.6" Gaming Laptop - Intel Core i5 - 8GB Memory - NVIDIA GeFo…

【讨论】:

    【解决方案2】:

    另一种解决方案。

    from simplified_scrapy import SimplifiedDoc,req,utils
    html = '''
    <h1 class="it-ttl" itemprop="name" id="itemTitle">
     <span class="g-hdn">Details about  &nbsp;</span>
     Acer - Nitro 5 15.6" Gaming Laptop - Intel Core i5 - 8GB Memory - NVIDIA GeFo…
    </h1>
    '''
    doc = SimplifiedDoc(html)
    item_names = doc.selects('h1.it-ttl').span.nextText()
    
    print(item_names)
    

    结果:

    ['Acer - Nitro 5 15.6" Gaming Laptop - Intel Core i5 - 8GB Memory - NVIDIA GeFo…']
    

    这里有更多示例。 https://github.com/yiyedata/simplified-scrapy-demo/tree/master/doc_examples

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-03
      • 2017-02-07
      • 2012-04-17
      • 1970-01-01
      • 1970-01-01
      • 2019-08-20
      • 1970-01-01
      • 2010-09-07
      相关资源
      最近更新 更多