使用urllib的Python网络爬虫

时间:2015-11-02 19:10:35

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

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

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但我找不到答案。

1 个答案:

答案 0 :(得分:3)

你忘记了一件小事:

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

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