2021-07-21

爬取豆瓣TOP电影各个电影的链接

from bs4 import BeautifulSoup
import urllib.request,urllib.error
import re
#爬取网页
findLink = re.compile(r'<a href="(.*?)">')
def main():
    baseurl="https://movie.douban.com/top250?start="
    datalist=getDate(baseurl)
    #savepath=".\\豆瓣电影Top250.xls"





def getDate(baseurl):
    datalist = []
    for i in range(0,1): #调用函数访问网页十次
        url=baseurl + str(i*25)
        html=askURL(url)
        soup=BeautifulSoup(html,"html.parser")
        for item in soup.find_all('div',class_='item'):
            item=str(item)
            link=re.findall(findLink,item)[0]
            print(link)

    return datalist




def askURL(url):
    head={
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.67"
    }
    request=urllib.request.Request(url,headers=head)
    html=''
    try:
        response=urllib.request.urlopen(request)
        html=response.read().decode('utf-8')
        #print(html)
    except urllib.error.URLError as e:
        if hasattr(e,'code'):
            print(e.code)
        if hasattr(e,'reason'):
            print(e.reason)
    return html

if __name__ == '__main__':
    main()







上一篇:python爬虫第1练url lib


下一篇:python urllib模块