Python 使用漂亮的汤只考虑网页内容的某一部分 我怎样才能有一个漂亮的汤,只考虑网页的某个部分?
例如,我只想在页面上“当前查看次数最多”之后选择所有Python 使用漂亮的汤只考虑网页内容的某一部分 我怎样才能有一个漂亮的汤,只考虑网页的某个部分?,python,web-scraping,html-parsing,beautifulsoup,webpage,Python,Web Scraping,Html Parsing,Beautifulsoup,Webpage,例如,我只想在页面上“当前查看次数最多”之后选择所有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') 查找句子,但这无助于确定我想要的内容部
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')
查找句子,但这无助于确定我想要的内容部分。查找包含浏览次数最多的文章的
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
这里的诀窍是,我们首先要找到查看次数最多的
链接的容器-它是拥有查看次数最多的类的div
。您可以在浏览器开发人员工具的帮助下对其进行检查 谢谢你。顺便说一句,如果网页上没有“mostViewed”类,只有一行“MostView”文本怎么办?@MarkK那么你可以使用css选择器,或者只需找到父对象,然后用div
标记查找所有子对象。或者,切换到lxml
并使用xpath表达式。嗯,真的有很多选择。