首页 > 解决方案 > Beautiful Soup Error: Trying to retrieve data from web page returns empty array

问题描述

I am trying to download a list of voting intention opinion polls from this web page using beautiful soup. However, the code I wrote returns an empty array or nothing. The code I used is below:

The page code is like this:

<div class="ST-c2-dv1 ST-ch ST-PS" style="width:33px"></div>
    <div class="ST-c2-dv2">41.8</div>

That's what I tried:

import requests
from bs4 import BeautifulSoup

request = requests.get(quote_page) # take the page link
page = request.content  # extract page content

soup = BeautifulSoup(page, "html.parser")

# extract all the divs
for each_div in soup.findAll('div',{'class':'ST-c2-dv2'}):
    print each_div

At this point, it prints nothing. I've tried also this:

tutti_a = soup.find_all("html_element", class_="ST-c2-dv2")

and also:

tutti_a = soup.find_all("div", class_="ST-c2-dv2")

But I get an empty array [] or nothing at all

标签: python-3.xweb-scrapingbeautifulsoup

解决方案


我认为您可以使用以下网址

import requests
from bs4 import BeautifulSoup as bs
import pandas as pd
r = requests.get('https://www.marktest.com/wap/a/sf/v~[73D5799E1B0E]/name~Dossier_5fSondagensLegislativas_5f2011.HighCharts.Sondagens.xml.aspx')
soup = bs(r.content, 'lxml')

results = []
for record in soup.select('p'):
    results.append([item.text for item in record.select('b')])
df = pd.DataFrame(results)
print(df)

第 5、6、7、8、9、10 列对应于 PS、PSD、CDS、CDU、Bloco、Outros/Brancos/Nulos

您可以删除不需要的列,添加适当的标题等。


推荐阅读