python - 熊猫:如果除外,重复当前关键字的功能
我已经建立了一个网络刮刀。程序将searchterm输入搜索框并获取结果。 Pandas
在列中逐行浏览电子表格以检索每个搜索词。
有时页面无法正确加载,提示刷新。
我需要一种方法让它重复该功能并尝试相同的 searchterm如果失败。现在,如果我return
,它会转到电子表格中的下一行。
import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
df = pd.read_csv(searchterms.csv, delimiter=",")
def scrape(searchterm):
#Loads url
searchbox = driver.find_element_by_name("searchbox")
searchbox.clear()
searchbox.send_keys(searchterm)
print "Searching for %s ..." % searchterm
no_result = True
while no_result is True:
try:
#Find results, grab them
no_result = False
except:
#Refresh page and do the above again for the current searchterm - How?
driver.refresh()
return pd.Series([col1, col2])
df[["Column 1", "Column 2"]] = df["searchterm"].apply(scrape)
#Executes crawl for each line in csv
最佳答案:
1 个答案:
答案 0 :(得分:1)
try
except
构造附带else
子句。如果一切正常,则执行else
块。 :
def scrape(searchterm):
#Loads url
no_result = True
while no_result:
#Find results, grab them
searchbox = driver.find_element_by_name("searchbox")
searchbox.clear()
try: #assumes that an exception is thrown if there is no results
searchbox.send_keys(searchterm)
print "Searching for %s ..." % searchterm
except:
#Refresh page and do the above again for the current searchterm
driver.refresh()
else: # executed if no exceptions were thrown
no_results = False
# .. some post-processing code here
return pd.Series([col1, col2])
(无论如何都会执行finally
块,这对于不依赖于前面代码成功或失败的清理任务非常有用)
另外,请注意空except
捕获任何异常,几乎不是一个好主意。我不熟悉selenium
如何处理错误,但是在捕获异常时,您应该指定您希望处理的异常。这样,如果发生意外异常,您的代码将中止,您将知道发生了一些不好的事情。
这就是为什么你还应该尝试在try
块中保留尽可能少的行。
本文经用户投稿或网站收集转载,如有侵权请联系本站。