【问题标题】:Python web crawler using urllib使用 urllib 的 Python 网络爬虫
【发布时间】:2015-11-02 19:10:34
【问题描述】:

我正在尝试从网页/网站中提取数据。这是我的代码:

from urllib import urlopen
from BeautifulSoup import BeautifulSoup
import re

webpage=urlopen('http://www.xxxxxxxxx.com').read()
patFinderTitle=re.compile('<title>(.*)</title>')

patFinderLink=re.compile('<link rel.*href="(.*)"/>')

findPatTitle=re.findall(patFinderTitle,webpage)
findPatLink=re.findall(patFinderLink,webpage)


listIterator=[]
listIterator[:]=range(2,16)

for i in listIterator:

    print findPatTitle[i]
    print findPatLink[i]
    print "\n"

    articlepage=urlopen(findPatLink[i]).read()

    divbegin=articlepage.find('<div class="">')
    article=articlepage[divbegin:(divbegin+1000)]

    soup=BeautifulSoup(article)

    paralist=soup.findAll('<p>')
    for i in paralist:
         print i

我想列出网页中的标题和所有链接。当我运行脚本时,它会引发错误:

Traceback (most recent call last):
File "justdialcrawl.py", line 21, in <module>
print findPatTitle[i]
IndexError: list index out of range

我尝试在 Google 上搜索,但找不到答案。

【问题讨论】:

  • 您为什么使用非常旧的BeautifulSoup 版本?运行pip install beautifulsoup4,然后在你的程序中使用from bs4 import BeautifulSoup

标签: beautifulsoup web-crawler python-requests urllib python-2.5


【解决方案1】:

你忘了一件小事:

webpage=urlopen('http://www.xxxxxxxxx.com').read()
#                                  this -> ^^^^^^^

您的代码刚刚生成了一个urlopen 对象并将其分配给webpage。要分配页面的内容,您需要.read()

【讨论】:

  • 是的,我改变了,谢谢 :) 但现在再次弹出错误,说列表索引超出范围,请在更新的问题上找到错误
  • @SJith 你在你的内部for 循环以及外部循环中使用i。将其中一个更改为其他内容。
  • 我尝试将内部 for 循环变量更改为 __ j __ 但我仍然看不到任何更改:(
  • @SJith 您能否提供您正在搜索的实际站点,以便我测试您的代码?但与此同时,您收到findPatTitle 错误的原因是因为您的迭代器i2 开始,但通常HTML 页面中只有一个&lt;title&gt;...&lt;/title&gt; 字段,即@987654331 @ 里面只有一项,在索引0
  • @SJith 同样,与listIterator 的整个业务完全没有必要。只需使用for i in range(2, 16): 就可以了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-08
  • 1970-01-01
相关资源
最近更新 更多