【问题标题】:If condition for adding information into a dataframe如果将信息添加到数据框中的条件
【发布时间】:2021-11-03 21:11:57
【问题描述】:

我需要创建一个包含以下列的数据框:

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)

代码应该执行以下操作:

  • 对于x = stackoverflow.com(这只是一个工作url的例子),打开chrome;如果有信息,则提取有关组织和国家的信息;如果没有,将“缺失”添加到数据框中;退出铬;
  • 对于x = livevsfox.ca,打开chrome;如果有信息,则提取有关组织和国家的信息;如果没有,则在OrganisationCountry 列中添加“缺失”;退出 Chrome。

那么预期的输出是:

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(或NA,由您决定);
  • 否则,网络会在数据框中添加信息(所有者和国家/地区)。

希望你能提供一些帮助。

【问题讨论】:

  • 没有 class= 'force--h4' 的 div,这就是您在 xpath 中寻找的内容
  • 我觉得你想用python来做这个很有趣!您是否尝试在这些网站上获取 ICANN/WHOIS 类型信息?见newbedev.com/check-whether-domain-is-registered
  • 感谢桂维曼。老实说,我不知道 pythonwhois 库。

标签: python pandas selenium web-scraping selenium-chromedriver


【解决方案1】:

我已经找到了解决这个问题的方法。

首先,我检测h2 class元素如下:

  message = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR,"section.section div.container h2"))).text

然后,我检查message 是否包含特定文本;例如。

if 'Sorry,' in message:

如果是这样,那么我将值附加到我将添加到数据框中的列表中:

 organisation.append('Missing') 
 country.append('Missing')

代码:

try:

      message = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR,"section.section div.container h2"))).text
      if 'Sorry,' in message: 
                    
        organisation.append('Missing') 
        country.append('Missing')
except: 
      continue

【讨论】:

    猜你喜欢
    • 2021-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-16
    • 2021-12-14
    • 2017-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多