如何修复BeautifulSoup/selenium在同一网站上工作的某些页面,但不是所有页面?

2024-09-27 20:16:49 发布

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

我正在努力刮去:https://www.prosportstransactions.com/football/Search/SearchResults.php?Player=&Team=&BeginDate=&EndDate=&PlayerMovementChkBx=yes&submit=Search&start=0的每一页

现在我有了迭代更改URL的代码。然后将URL传递到selenium驱动程序中,以获取HTML内容。然后将内容放入BeautifulSoup进行处理。我的问题是我随机得到以下消息(随机发生在不同的页面上,导致程序崩溃)。没有一致的页面失败):

Traceback (most recent call last):
  File "scrape.py", line 89, in <module>
   i, i + 5000)
  File "scrape.py", line 37, in scrapeWebsite
    extractedInfo = info.findAll("td")
AttributeError: 'NoneType' object has no attribute 'findAll'

i,i+5000用于循环以迭代方式更新页面,因此这并不重要。你知道吗

下面是执行HTML抓取的代码:

driver = webdriver.Chrome(executable_path='/Users/Downloads/chromedriver')
print(start, stop)


madeDict = {"Date": [], "Team": [], "Name": [], "Relinquished": [], "Notes": []}

#for i in range(0, 214025, 25):
for i in range(start, stop, 25):
    print("Current Page: " + str(i))
    currUrl = url + str(i)
    driver.get(currUrl)
    driver.implicitly_wait(100
    soupPage = BeautifulSoup(driver.page_source, 'html.parser')
    #page = urllib2.urlopen(currUrl)
    #soupPage = BeautifulSoup(page, 'html.parser')

    # #Sleep the program to ensure page is fully loaded
    # time.sleep(1)

    info = soupPage.find("table", attrs={'class': 'datatable center'})
    extractedInfo = info.findAll("td")

我猜页面没有完成加载,所以当它试图抓取内容时,标签可能不在那里。但是,我认为Selenium防止了动态加载网页的问题,以确保在BeautifulSoup获取信息之前页面已完全加载。我在看其他帖子,有些人说我需要等待程序动态加载页面,但我尝试了,仍然是同样的错误。你知道吗


Tags: 代码ininfourl内容searchdriverpage
1条回答
网友
1楼 · 发布于 2024-09-27 20:16:49

不使用selenium执行,而是使用请求。你知道吗

import requests
from bs4 import BeautifulSoup

url='https://www.prosportstransactions.com/football/Search/SearchResults.php?Player=&Team=&BeginDate=&EndDate=&PlayerMovementChkBx=yes&submit=Search&start='

for i in range(0, 214025, 25):
    print("Current Page: " + str(i))
    r=requests.get(url + str(i))
    soup = BeautifulSoup(r.content)
    info = soup.find("table", attrs={'class': 'datatable center'})
    extractedInfo = info.findAll("td")
    print(extractedInfo)

相关问题 更多 >

    热门问题