[英]For Loops while using selenium for webscraping Python
我正在嘗試從以下網站上抓取信息: https://www.axis.net/forum/companies/united-states-family-offices/
我正在嘗試抓取每個家族辦公室的描述,所以“ https://www.axis.net/forum/companies/united-states-family-offices/ “+insert_company_name” 是我需要抓取的頁面。
所以我寫了下面的代碼來測試程序只有一頁:
from bs4 import BeautifulSoup as soup
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome('insert_path_here/chromedriver')
driver.get("https://network.axial.net/company/ansaco-llp")
page_source = driver.page_source
soup2 = soup(page_source,"html.parser")
soup2.findAll('axl-teaser-description')[0].text
這適用於單頁,只要描述沒有“顯示完整描述”下拉按鈕。 我會把它留到另一個問題上。
我寫了以下循環:
#Note: Lst2 has all the names for the companies. I made sure they match the webpage
lst3=[]
for key in lst2[1:]:
driver.get("https://network.axial.net/company/"+key.lower())
page_source = driver.page_source
for handle in driver.window_handles:
driver.switch_to.window(handle)
word_soup = soup(page_source,"html.parser")
if word_soup.findAll('axl-teaser-description') == []:
lst3.append('null')
else:
c = word_soup.findAll('axl-teaser-description')[0].text
lst3.append(c)
print(lst3)
當我運行循環時,所有值都顯示為“null”,即使是那些沒有“點擊查看完整描述”按鈕的值。
我編輯了循環以打印出“word_soup”,如果我在沒有循環的情況下運行它並且沒有描述文本,那么頁面會有所不同。
我不明白為什么循環會導致這種情況,但顯然確實如此。 有誰知道如何解決這個問題?
找到解決方案。 在 driver.get 之后暫停程序 3 秒:
import time
lst3=[]
for key in lst2[1:]:
driver.get("https://network.axial.net/company/"+key.lower())
time.sleep(3)
page_source = driver.page_source
word_soup = soup(page_source,"html.parser")
if word_soup.findAll('axl-teaser-description') == []:
lst3.append('null')
else:
c = word_soup.findAll('axl-teaser-description')[0].text
lst3.append(c)
print(lst3)
我看到該頁面使用 javascript 來生成文本,這意味着它不會出現在頁面源中,這很奇怪但沒關系。 我不太明白為什么你只是迭代並切換到你打開的 Selenium 的所有實例,但你肯定不會在頁面源/beautifulsoup 中找到描述。
老實說,如果可以的話,我個人會尋找一個更好的網站,否則,您將不得不使用 selenium 進行嘗試,這既低效又可怕。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.