使用BeautifulSoup进行网页抓取时出错

2024-09-29 23:27:12 发布

您现在位置:Python中文网/ 问答频道 /正文

试图提取巴西足球锦标赛表格中的球队列表,搜索正确的标签和等级,我没有得到任何返回数据。 我曾试图阅读BS4网站上的官方文档,但仍然无法解决此问题。 如果有人能帮助我,我将不胜感激。下面是使用的屏幕截图和代码

页面:https://i.stack.imgur.com/9YTJf.png

通过选择器使用元素检查器:https://i.stack.imgur.com/asMng.png

开发者工具窗口:https://i.stack.imgur.com/fAKZJ.png

没有返回数据的搜索:https://i.stack.imgur.com/U2S5W.png

from bs4 import BeautifulSoup
import lxml, requests

r = requests.get('https://www.google.com/search?q=Tabela+do+Campeonato+Brasileiro+de+Futebol&oq=Tabela+do+Campeonato+Brasileiro+de+Futebol&aqs=chrome..69i57.241j0j1&sourceid=chrome&ie=UTF-8#sie=lg;/g/11fmzksb3y;2;/m/0fnk7q;st;fp;1;;')

page = r.text
soup = BeautifulSoup(page, 'lxml')

for i in soup.find_all('span', class_='ellipsisize hsKSJe'):
    print(i.text)

Tags: 数据httpsimportcompngstackderequests
1条回答
网友
1楼 · 发布于 2024-09-29 23:27:12

我相信这个问题是因为您正试图使用BeautifulSoup从动态页面获取数据。为此,您可以将selenium与chrome driver一起使用。我将其保存在系统驱动器上自己的文件夹(bin\chromedriver.exe)中

例如,下面给出了前五行(没有足够的持久性来确定其他所有行的选择器,对不起!)

from selenium import webdriver
import pandas as pd

URL = 'https://www.google.com/search?q=Tabela+do+Campeonato+Brasileiro+de+Futebol&oq=Tabela+do+Campeonato+Brasileiro+de+Futebol&aqs=chrome..69i57.241j0j1&sourceid=chrome&ie=UTF-8#sie=lg;/g/11fmzksb3y;2;/m/0fnk7q;st;fp;1;;'
#webdriver and get data from dynamic page
dr = webdriver.Chrome(executable_path=r'C:/bin/chromedriver.exe')
dr.get(URL)
#get table data by xpath
data = dr.find_element_by_css_selector('#rso').get_attribute('outerHTML')
dr.close()

#get data as dataframe
raw = pd.read_html(data)[0]
#organize retrieved columns
labels = raw.columns.values[1:11]
table = raw[labels]
#delete excess column
del table['Club']
table.columns = labels[:-1] #ignore the last value

#view table (can't post an image yet! new here :))

相关问题 更多 >

    热门问题