【问题标题】:how to split the data that i extracted from a webpage and append each line to list?如何拆分我从网页中提取的数据并将每一行附加到列表中?
【发布时间】:2021-02-14 15:10:53
【问题描述】:

作为我项目的一部分,我从网页上抓取数据并删除了所有标签。现在我想在新行处拆分数据并将其附加到列表中,以便我可以使用列表索引轻松访问我抓取的数据的任何行。 这是我在 python 中的代码

import requests
def getdata(f):
    s = requests.Session()
    login_data = {'username': f, 'x': '112', 'y': '38'
                  }
    headers = {'User-Agent':
                   'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                   'Chrome/88.0.4324.146 Safari/537.36'}
    p = s.post('http://202.53.81.30/results/vr17r2ra/hno.php', data=login_data, headers=headers)
    soup = BeautifulSoup(p.content, 'html5lib')
    da = soup.find('table', attrs={'align': 'center', 'border': '1'})
    for row in da.findAll("tr"):
        so = BeautifulSoup(row.text, 'html.parser')
        text = so.get_text()
        text1 = text.rstrip()
        print(text1[1])

如果我们执行并使用直到text = so.get_text() f = 198w1a0561 到 getdata 函数,我得到了我抓取的全部数据。

text1 = text.rstrip()
print(text1[1])

为了解决它,我确实喜欢这样做。但我无法使用它访问文本的特定行? 相反,我该怎么办? 怎么办?

【问题讨论】:

    标签: python data-extraction


    【解决方案1】:

    so 无需再次拨打BeautifulSoup。相反,您可以运行row.find_all('th', {'align': 'CENTER'}) 来获取相关的表行。您可以使用text.strip() 来获取干净的文本。我已将其包含在列表理解中:

    import requests
    from bs4 import BeautifulSoup
    
    def getdata(f):
        s = requests.Session()
        login_data = {'username': f, 'x': '112', 'y': '38'
                      }
        headers = {'User-Agent':
                       'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                       'Chrome/88.0.4324.146 Safari/537.36'}
        p = s.post('http://202.53.81.30/results/vr17r2ra/hno.php', data=login_data, headers=headers)
        soup = BeautifulSoup(p.content, 'html5lib')
        da = soup.find('table', attrs={'align': 'center', 'border': '1'})
        return list(filter(None, [[i.text.strip() for i in row.find_all('th', {'align': 'CENTER'})] for row in da.find_all('tr')]))
    

    输出:

    [['1', '17CH1202A', 'Ex', '10'], ['2', '17EC1204A', 'A+', '9'], ['3', '17MC1206B', 'Ex', '10'], ['4', '17MA1201', 'Ex', '10'], ['5', '17CS1203', 'Ex', '10'], ['6', '17ME1205', 'A', '8'], ['7', '17CH1251', 'Ex', '10'], ['8', '17CS1252', 'Ex', '10']]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-26
      • 2021-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-14
      • 2020-04-03
      • 2019-06-28
      相关资源
      最近更新 更多