我需要创建一个包含以下列的数据框:
WEB | Country | Organisation
我从网站中提取这些信息:但是,有些网站的网站上没有任何信息。这导致我在更新数据框时遇到一些问题。不幸的是,该代码一次只能运行一个网站,否则会出现验证码。
请参阅下面的代码以了解各个输出:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import pandas as pd
element=[]
organisation=[]
x=['stackoverflow.com'] # ['livevsfox.ca'] I would suggest to try first one, then the other one
frame_dict={}
element.append(x) # I am keeping this just because I'd like to consider a for loop in future
chrome_options = webdriver.ChromeOptions()
driver=webdriver.Chrome('path')
response=driver.get('website/'+x) # here x should stackoverflow.com, then the other web
try:
wait = WebDriverWait(driver, 30)
driver.execute_script("window.scrollTo(0, 1000)")
try:
error = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR,"section.selection div.container h2"))) # updated after answer from another post and comment below
except:
continue
# Country
c = wait.until(EC.visibility_of_element_located((By.XPATH, "//div[text()='Company data']/../following-sibling::div/descendant::b[text()='Country']/../following-sibling::div"))).text
country.append(c)
# Organisation
try:
org=wait.until(EC.visibility_of_element_located((By.XPATH, "//div[text()='Company data']/../following-sibling::div/descendant::b[text()='Organisation']/../following-sibling::div"))).text
organisation.append(org)
except:
organisation.append("Data not available")
except:
break
driver.quit()
frame_dict.update({'WEB': element, 'Organisation': organisation, 'Country': country})
df=pd.DataFrame.from_dict(frame_dict)
该代码应该执行以下操作:
- for
x = stackoverflow.com
(这只是工作网址的示例),打开chrome;如果有信息,则提取有关组织和国家的信息;如果没有,则将“Missing”添加到数据框中;退出铬;
- for
x = livevsfox.ca
,打开chrome;如果有信息,则提取有关组织和国家的信息;如果没有,则添加“缺失”Organisation
and Country
列;退出铬。
那么预期的输出将是:
WEB Country Organisation
stackoverflow.com US Stack Exchange, Inc.
livevsfox.ca Missing Missing
livevsfox.ca
事实上,返回以下消息:
Sorry, livevsfox.ca could not be found or reached (error code 404)
当我查找 stackoverflow.com 时没有出现该消息。
由于 stackoverflow.com 有国家和组织,我可以在数据框中添加此信息,但我不能对 livevsfox.ca 执行相同的操作。
我认为可能的解决方案如下:
- 检查是否
h2 class
元素包含上面的消息("Sorry, x could not be found or reached (error code 404)"
) :这意味着网络没有检测到信息;
- 如果网络没有信息,则添加
Missing
(or NA
,由您决定)在数据框中;
- 否则,网络将在数据框中添加信息(所有者和国家/地区)。
我希望你能提供一些帮助。