苏执 发表于 2021-2-18 12:38:03

python爬虫豆瓣新人求助

from bs4 import BeautifulSoup   #网页解析,获取数据
import urllib.request,urllib.error      #制定URL,获取网页数据

def main():
    baseurl = "https://movie.douban.com/top250?start="
    #1.爬取网页
    datalist = getData(baseurl)
    savepath = "豆瓣电影Top250.xls"
    #3.保存数据
    saveData(savepath)
    askUPL("https://movie.douban.com/top250?start=")

#爬取网页
def getData(baseurl):
    datalist = []
    for i in range(0,10):
      url = baseurl+str(i*25)
      html = askUPL(url)
      #2.逐一解析数据
    return datalist

#得到指定一个URL的网页内容
def askURL(url):
    head = {
      "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36 Edg/88.0.705.68"
    }
    request = urllib.request.Request(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

    # 保存数据
def saveData(savepath):
    print("save....")

if __name__ == "__main__":
    main()


为什么一直运行不出来啊?一直显示这个{:10_266:} {:10_266:}
D:\douban\venv\Scripts\python.exe D:/douban/venv/spider.py
Traceback (most recent call last):
File "D:/douban/venv/spider.py", line 51, in <module>
    main()
File "D:/douban/venv/spider.py", line 13, in main
    datalist = getData(baseurl)
File "D:/douban/venv/spider.py", line 24, in getData
    html = askUPL(url)
NameError: name 'askUPL' is not defined

Cool_Breeze 发表于 2021-2-18 18:58:04

ameError: name 'askUPL' is not defined
为什么askUPL未声明呢?
是不是顺序的问题?

YunGuo 发表于 2021-2-19 00:34:48

本帖最后由 YunGuo 于 2021-2-19 00:36 编辑

html = askUPL(url)
这里错了一个字母,也就是报错的第24行代码,你定义的函数名是askURL,打成了askUPL
页: [1]
查看完整版本: python爬虫豆瓣新人求助