m0_51953984 2021-06-13 17:01 采纳率: 100%
浏览 364
已采纳

爬虫爬取该网站时返回空列表

import requests
from bs4 import BeautifulSoup
import csv

def getHtml(url):
    try:
        r=requests.get(url)
        r.raise_for_status()
        r.encoding=r.apparent_encoding
        return r.text
    except:
        return "fail"
    
def getDATA(ulist,html):
    soup=BeautifulSoup(html,'html.parser')
    table=soup.find_all('tr')
    for row in table:
        cols=[col.text for col in row.find_all('td')]
        if len(cols)==0 or not cols[0].isdigit():
            continue
        ulist.append(cols)

def main():
    unifo=[]
    url='https://www.phb123.com/hangye/qiche/index_1.html'
    html=getHtml(url)
    getDATA(unifo,html)
    print(html)
    print('*'*20)
    print(unifo)
main()

有大佬能帮忙解决一下吗?

  • 写回答

3条回答 默认 最新

  • CSDN专家-showbo 2021-06-13 18:04
    关注

    第一列不是包含了换行和空白,导致是否数字判断失败,要去掉空白就可以了,加下面加粗的内容,帮助到你可以点击采纳吗,谢谢~~

    def getDATA(ulist,html):
        soup=BeautifulSoup(html,'html.parser')
        table=soup.find_all('tr')
        for row in table:
            cols=[col.text for col in row.find_all('td')]
            if len(cols)==0 or not cols[0].strip().isdigit():
               continue
            ulist.append(cols)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?