美丽的汤解析网址以获取另一个网址数据

tim*_*tim 25 html python parsing beautifulsoup

我需要解析一个url以获取链接到详细信息页面的URL列表.然后,从该页面我需要从该页面获取所有详细信息.我需要这样做,因为详细页面URL不会定期递增和更改,但事件列表页面保持不变.

基本上:

example.com/events/
    <a href="http://example.com/events/1">Event 1</a>
    <a href="http://example.com/events/2">Event 2</a>

example.com/events/1
    ...some detail stuff I need

example.com/events/2
    ...some detail stuff I need
Run Code Online (Sandbox Code Playgroud)

Tau*_*uir 64

import urllib2
from BeautifulSoup import BeautifulSoup

page = urllib2.urlopen('http://yahoo.com').read()
soup = BeautifulSoup(page)
soup.prettify()
for anchor in soup.findAll('a', href=True):
    print anchor['href']
Run Code Online (Sandbox Code Playgroud)

它会为您提供网址列表.现在,您可以迭代这些URL并解析数据.

  • inner_div = soup.findAll("div", {"id": "y-shade"}) 这是一个例子.您可以浏览BeautifulSoup教程.


lin*_*eak 5

使用 urllib2 获取页面,然后使用 beautiful soup 获取链接列表,也可以尝试 scraperwiki.com

编辑:

最近发现:通过 lxml 使用 BeautifulSoup

from lxml.html.soupparser import fromstring
Run Code Online (Sandbox Code Playgroud)

比 BeautifulSoup 好很多。它可以让你做 dom.cssselect('你的选择器') 这是一个救星。只需确保您安装了良好版本的 BeautifulSoup 即可。3.2.1 工作是一种享受。

dom = fromstring('<html... ...')
navigation_links = [a.get('href') for a in htm.cssselect('#navigation a')]
Run Code Online (Sandbox Code Playgroud)


dis*_*use 5

对于遇到这种情况的下一群人,由于v3不再更新,BeautifulSoup已经升级到v4.

$ easy_install beautifulsoup4

$ pip install beautifulsoup4
Run Code Online (Sandbox Code Playgroud)

在Python中使用...

import bs4 as BeautifulSoup
Run Code Online (Sandbox Code Playgroud)

  • 我现在还建议通过urllib2使用Python请求。是的,它是一个非核心模块,但是使用它会为您省去很多麻烦。有人提议将其作为核心的一部分,但最终决定反对。简短介绍-https://gist.github.com/bradmontgomery/1872970文档-http://docs.python-requests.org/zh/master/ (3认同)