Python网络数据采集----学习心得

最近在学一本爬虫的书,但是发现书中有不少代码是错误的(或者是本人的问题,但我没意识到),无论如何,本帖会记录下我的学习历程,希望不对之处能得到高手的指正.

(持续更新)

1.第三章:P28

from urllib.request import urlopen
from bs4 import BeautifulSoup
import random
import datetime
import re


def GetLinks(url_name):
    html =urlopen("https://en.wikipedia.org"+url_name)
    beautifulsoup_object = BeautifulSoup(html)
    url_list = []
    for link in beautifulsoup_object.find("div", {"id": "bodyContent"}).findAll("a",
                                                                                href=re.compile("^(/wiki/)((?!:).)*$")):
        if 'href' in link.attrs:
            url_list.append(link.attrs['href'])
    return url_list

get_links = GetLinks('/wiki/Kevin_Bacon')
random.seed(datetime.datetime.now())
while len(get_links)>0:
    new_url = get_links[random.randint(0, len(get_links)-1)]
    print(new_url)
    get_links = GetLinks(new_url)

与书中不同之处在于new_url = get_links[random.randint(0, len(get_links)-1)].attrs["href"]
在运行时发现报错,于是删除.attrs["href"]
回头琢磨了一下,是因为我在GetLinks函数中已经提取href,存储在get-links中的已经是字符串
程序正常运行,效果如下:
这里写图片描述
最后出现代码Process finished with exit code -1 说明程序正常运行完毕.

猜你喜欢

转载自blog.csdn.net/weixin_40624269/article/details/82025882