账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    (求助)Python爬虫代码 不知道错在哪里。。。。
    29
    0
    >>> import requests
    >>> from bs4 import BeautifulSoup
    >>> url = "http://www.zgxxb.com.cn/jqtt/201807190013.shtml"
    >>> allUniv = []
    >>> def getHtmlText(url):
        try:
    
            r = requests.get(url, timeout=30)
            r.raise_for_status()
            r.encoding = 'utf-8'
            return r.text
        except:
    
            return ""
    
        
    >>> def fillUnivList(soup):
        trs=soup.find_all('tr')
        for tr in trs:
            tds = tr.find_all('td')
            if len(tds)==0:
                continue
            oneUniv = []
            for td in tds:
                oneUniv.append(td.string)
            allUniv.append(oneUniv)
    
            
    >>> def printUnivList(num):
        print("{:^5}{:^10}{:^8}{:^8}".format("省份","播种面积","总产量","每公顷产量"))
        for i in range(num):
            u = allUniv[i]
            print("{:^5}{:^10}{:^8}{:^8}".format(u[0],eval(u[1]),eval(u[2]),eval(u[3])))
    
            
    >>> def main(num):
        url = 'http://www.zgxxb.com.cn/jqtt/201807190013.shtml'
        html = getHtmlText(url)
        soup = BeautifulSoup(html, "html.parser")
        fillUnivList(soup)
        printUnivList(num)
    
    
    >>> if __name__ == '__main__':
        main(30)
    Traceback (most recent call last):
      File "<pyshell#42>", line 2, in <module>
        main(30)
      File "<pyshell#38>", line 6, in main
        printUnivList(num)
      File "<pyshell#30>", line 5, in printUnivList
        print("{:^10}{:^10}{:^10}{:^10}".format(u[0],eval(u[1]),eval(u[2]),eval(u[3])))
    0
    打赏
    收藏
    点击回答
    您的回答被采纳后将获得:提问者悬赏的 10 元积分
        全部回答
    • 0
    更多回答