【问题标题】:Creating a dataframe using contents of paragraphs in each webpage by web scraping通过网页抓取使用每个网页中的段落内容创建数据框
【发布时间】:2022-01-09 15:06:17
【问题描述】:

我正在尝试使用 selenium 和 beautifulsoup 抓取特定网站。想法是在熊猫数据框中获取每个页面的链接及其对应的段落。

所以生成的数据框会是这样的

     Link                              Paras
https://www.<website>.com      contents of all <p> tags
   /specific_page.html    

为此,我使用以下代码 sn-ps:

driver = webdriver.Chrome(executable_path='D:\WebScrapp\chromedriver.exe')
driver.get(url)
elem = driver.find_elements_by_xpath("//a[@href]")
link=[]
para = []
for e in elem:
    try:
        page = requests.get(e.get_attribute('href'))
        soup = bs(page.content,'lxml')
        paras = soup.find_all('p')
        for p in paras:
            if '<seacrh_strng>' in p.text:
                link.appned(str(e.get_attribute('href')))
                para.append(p.text)
    except:
        print('InvalidSchema: No connection adapters')
df = pd.DataFrame(zip(link,para),columns=['Link','Para'])

有了以上内容,我面临以下问题:

  1. 大多数时候(或elem 中的大多数元素)它会被except 阻塞,从而打印'InvalidSchema: No connection adapters'
  2. 上述技术相当缓慢。

例如。我尝试过像https://www.cognizant.comhttps://www.sas.comhttps://www.bmc.com 这样的网址,但数据框中没有任何内容。很难相信这些网站没有使用&lt;p&gt;作为标签!!

事实上我已经尝试过paras = soup.find_all(re.compile('^h[1-6]$')),但没有运气!

我错过了什么?

【问题讨论】:

    标签: python selenium beautifulsoup


    【解决方案1】:

    我建议像这样重构您的代码:

    import pandas as pd
    import requests
    from bs4 import BeautifulSoup
    from selenium import webdriver
    
    driver = webdriver.Chrome(
        executable_path="D:\WebScrapp\chromedriver.exe"
    )
    driver.get("https://www.bmc.com")  # for testing purposes
    
    elements = driver.find_elements(by="xpath", value="//a[@href]")
    
    results = {"link": [], "ptag": []}
    
    for element in elements:
        try:
            url = element.get_attribute("href")
            response = requests.request(method="get", url=url)
            parsed_html = BeautifulSoup(response.content, "lxml", from_encoding="utf-8")
            for p_tag in parsed_html.find_all("p"):
                results["link"].append(url)
                results["ptag"].append(p_tag.text)
        except:
            continue
    

    然后:

    df = pd.DataFrame(results)
    
    print(df.sample(4))
    # Output
                                                      link                                               ptag
    55                               https://www.bmc.com/#  Gartner names BMC a Leader in the ITSM Magic Q...
    138  https://www.bmc.com/it-solutions/bmc-helix-ope...           Winner of the 2021 AI Breakthrough Award
    303       https://www.bmc.com/it-solutions/devops.html           Speak to a rep about your business needs
    43                               https://www.bmc.com/#  Drive innovation through agility, customer cen...
    

    【讨论】:

      猜你喜欢
      • 2023-02-03
      • 2010-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-21
      相关资源
      最近更新 更多