Python 网页抓取索引

Python Web Scrape Index

我对任何形式的网页抓取都非常陌生,我一直在尝试进入 Python,我听说网页抓取是让自己接触 Python 的好方法.因此,经过多次 Google 搜索,我最终归结为使用两个强烈推荐的模块:Requests 和 BeautifulSoup。我已经阅读了相当多的内容,并且对如何使用它们有了基本的了解。

我找到了一个非常基本的网站(基本是没有太多内容或 javascript 之类的东西,使 HTML 的解析变得容易得多),我有以下代码:

import requests
from bs4 import BeautifulSoup

soup = BeautifulSoup(requests.get('http://www.basicwebs.co.uk/contact.htm').text)

for row in soup('div',{'id': 'Layer1'})[0].h2('font'):
    tds = row.text
    print tds

此代码有效。它产生以下结果:

BASIC
    WEBS
Contact details
Contact details

如果您花几分钟检查此页面上的代码,这就是正确的结果(我假设)。现在,问题是,虽然这段代码有效,但如果我想获得页面的不同部分怎么办?就像页面上声明 "If you are interested in having a website designed and hosted by us, please contact us either by e-mail or telephone." 的小段落一样 - 我的理解是将索引号简单地更改为相应的 header ,该文本位于下方,但是当我更改它时,我收到一条消息列表索引超出范围。

有人可以帮忙吗? (尽可能简单,如果可能的话)

我正在使用 Python 2.7.8

您需要的文本被属性 size=3 的字体标签包围,因此一种方法是选择第一次出现的文本,如下所示:

font_elements = soup('font', {'size': 3})

if font_elements:
     print font_elements[0].text

结果:

如果您有兴趣设计一个网站 由我们托管,请通过电子邮件或电话与我们联系。

你可以直接这样做:

soup('font',{'size': '3'})[0].text

但是,我想提请你注意你之前犯的错误。

soup('div',{'id': 'Layer1'})

this returns id='Layer1' 的 div 标签,可以是多个。所以它基本上是 returns 所有 HTML 元素的列表,其 div 标签有 id='Layer1' 但不幸的是你试图解析的 HTML 有一个这样的元素.所以它越界了。

您或许可以使用一些 python 的交互式解释器,例如 bpython 或 ipython 来测试您在一个对象中得到了什么。?快乐黑客!!!

from urllib.request import urlopen
from bs4 import BeautifulSoup

web_address=' http://www.basicwebs.co.uk/contact.htm'
html = urlopen(web_address)
bs = BeautifulSoup(html.read(), 'html.parser')

contact_info = bs.findAll('h2', {'align':'left'})[0]
for info in contact_info:
    print(info.get_text())