【问题标题】:Using BeautifulSoup only consider a certain part of contents of a webpage使用 BeautifulSoup 只考虑网页的某一部分内容
【发布时间】:2014-05-19 04:19:30
【问题描述】:

如何让 BeautifulSoup 只考虑网页内容的特定部分?

例如,我想在页面http://www.dailypress.com/ 上的“当前查看最多”之后提取所有div 标签。

是这样的:

from bs4 import BeautifulSoup
import urllib2

url = ' http://www.dailypress.com/ '
page = urllib2.urlopen(url)
soup = BeautifulSoup(page.read())

我可以使用:

str(soup).find(' Most viewed right now')

定位句子,但对确定我想要的内容部分没有帮助。

【问题讨论】:

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


    【解决方案1】:

    找到包含最多浏览文章的div,并找到其中的所有链接:

    >>> from bs4 import BeautifulSoup
    >>> import urllib2
    >>> import re
    >>> url = "http://www.dailypress.com"
    >>> soup = BeautifulSoup(urllib2.urlopen(url))
    >>> most_viewed = soup.find('div', class_=re.compile('mostViewed'))
    >>> for item in most_viewed.find_all('a'):
    ...     print item.text.strip()
    ... 
    Body of driver recovered from Chesapeake Bay Bridge-Tunnel wreck
    Hampton police looking for man linked to Friday's fatal apartment shooting
    Police identify suspect in Saturday's fatal shooting in Hampton
    Teen spice user: 'It's the new crack'
    When spice came to Gloucester
    

    这里的诀窍是我们首先找到Most Viewed 链接的容器——它是一个具有mostViewed 类的div。您可以在浏览器开发工具的帮助下检查它。

    【讨论】:

    • 感谢 alecxe。顺便说一句,如果网页上没有“mostViewed”类,而只有“Mostviewed right now”一行文字怎么办?
    • @MarkK 那么你可以使用css选择器,或者只是获取父级并找到所有带有div标签的子级。或者,切换到 lxml 并使用 xpath 表达式。嗯,确实有很多选择。
    猜你喜欢
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 2019-06-27
    • 2020-03-27
    • 2019-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多