首页 > 解决方案 > BeautifulSoup Finviz

问题描述

抱歉占用您的时间,我正在学习beautifulsoup,我想创建一个数据框,该数据框将从该URL复制表格

import pandas as pd

# To extract fundamental data
from bs4 import BeautifulSoup as bs
import requests

headers = {
    'User-Agent': 'Mozilla/5.0'}


base_url = 'https://finviz.com/screener.ashx?v=111&f=cap_smallover,sh_curvol_o500,sh_price_o3,sh_relvol_o1,sh_short_o10,ta_pattern_wedgedown&ft=3&o=-change'
html = requests.get(base_url, headers=headers)
soup = bs(html.content, "html.parser")
main_div = soup.find('div', attrs={'id': 'screener-content'})
table = main_div.find('table')
sub = table.findAll('tr')
rows = sub[5].findAll('td')

data = []

for row in rows:
    link = row.a
    if link is not None:

        data += link.get_text()

print(data)

但我得到的是:

['1', '1', 'A', 'P', 'I', 'A', 'g', 'o', 'r', 'a', ',', ' ', 'I', 'n', 'c', '.', 'T', 'e', 'c', 'h', 'n', 'o', 'l', 'o', 'g', 'y',

等等。

如何将所有这些数据保存到列表中,以便接下来我可以在 finviz screeners 表附近创建一个数据框?谢谢

标签: pythonpandasweb-scrapingbeautifulsoup

解决方案


您的代码中唯一的问题是:

data += link.get_text()

这种+=语法在 Python 中不起作用。要将元素添加到 a list,我们可以使用L.append(obj)。因此,您的代码可以更改为:

data.append(link.get_text())

推荐阅读