【问题标题】:Stop Crawling urls if class does not exist in table beautifulsoup and pandas如果表 beautifulsoup 和 pandas 中不存在类,则停止抓取 url
【发布时间】:2018-09-22 00:37:00
【问题描述】:

我正在使用 csv 文件中的 url 列表从 html 表中抓取和提取数据。当表格中不存在“style3”时,我想停止浏览网址。 我创建了一个函数,如果它不存在,它将返回 false,但我对如何实际实现它感到困惑。

任何关于解决方案或文献方向的建议都会有很大帮助,因为我无法在这里找到任何东西来帮助我解决这个问题。

我已经包含了 1 个带有 'style3' 的 url 和 1 个没有。感谢您的任何帮助。

http://www.wvlabor.com/new_searches/contractor_RESULTS.cfm?wvnumber=WV057808&contractor_name=&dba=&city_name=&County=&Submit3=Search+Contractors http://www.wvlabor.com/new_searches/contractor_RESULTS.cfm?wvnumber=WV057924&contractor_name=&dba=&city_name=&County=&Submit3=Search+Contractors

import csv
from urllib.request import urlopen
import pandas as pd
from bs4 import BeautifulSoup as BS

def license_exists(soup):
    contents = []
    with open('WV_urls.csv','r') as csvf:
        urls = csv.reader(csvf)
        for url in urls:
            if soup(class_='style3'):
                return True
            else:
                return False

contents = []
more = True
while more:
    df  = pd.DataFrame(columns=['WV Number', 'Company', 'DBA', 'Address', 'City', 'State', 'Zip','County', 'Phone', 'Classification*', 'Expires']) #initialize the data frame with columns
    with open('WV_urls.csv','r') as csvf: # Open file in read mode
        urls = csv.reader(csvf)
        for url in urls:
            contents.append(url) # Add each url to list contents
        for url in contents:  # Parse through each url in the list.
            page = urlopen(url[0]).read()
            df1, header = pd.read_html(page,header=0)#reading with header
            more = license_exists(?????)
            df=df.append(df1) # append to dataframe

            df.to_csv('WV_Licenses_Daily.csv', index=False)

【问题讨论】:

  • 查看页面/代码,您似乎正在搜索特定的wvnumber。是否存在每页可能有多个结果的情况(如果存在特定的wvnumber)?
  • 不。每个网址只有 1 条记录。
  • 当您说要停止浏览网址时,您是想跳出循环(并且不查找任何可能出现在该循环之后的网址)还是跳过尝试添加一个空行到您的数据框并继续到任何后续网址?
  • 而 license_exists() == false:
  • 跳出循环。最终目标是打破循环,通过电子邮件发送我收集的信息,然后从 csv 中删除我通过的网址

标签: python pandas dataframe beautifulsoup


【解决方案1】:

您可以使用单个 for 循环和 break 来执行此操作(不需要 while more):

lst = []
with open('WV_urls.csv','r') as csvf: # Open file in read mode
    urls = csv.reader(csvf)
    for url in urls:
        page = urlopen(url[0]).read()
        df1, header = pd.read_html(page, header=0)
        if license_exists(BS(page, ‘html.parser’)):
            # if the license is present we don't want to parse any more urls.
            # Note: we don't append this last result (should we?)
            break
        lst.append(df1)

df = pd.concat(lst)
df.to_csv('WV_Licenses_Daily.csv', index=False)

注意:这会从 DataFrames 列表中创建最终的 DataFrame,这比每次追加效率更高。

【讨论】:

  • 可能是if not license_exists(...) 我可能误解了这个功能。我可能会将其重命名为 is_empty 或其他名称。
  • 用你的回答,它一直告诉我没有什么可以连接的。我拿出了休息和 lst.append(df1) 并替换为 df=df.append(df1) 并且它起作用了。它就像一个魅力。我真的很感谢你的帮助。不知道我是否应该发布我现在拥有的作为答案,或者你应该修改你拥有的并且我接受你的回答。让我知道,以便我可以正确关闭它。
  • @RobK nothing to concatenate 意味着lst 是空的,这很奇怪。因为 df 没有在我上面的代码中定义,这听起来是错误的。你试过if not license_exists(...) 吗?
  • 正确。如果不是 license_exists 确实有效。 :) 给猫剥皮的方法不止一种?! :) 你介意我问你几个关于这个的问题吗?可以聊天吗?
  • 对我来说,写一个新问题更容易(如果您愿意,可以在此处添加链接),或者只是在这里提出问题(如果它们很短)。异步通信通常比聊天更可取。很高兴你成功了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-14
  • 2018-12-09
  • 1970-01-01
  • 2020-09-02
  • 2022-01-05
  • 2023-04-05
相关资源
最近更新 更多