Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 美丽的汤在错误上循环_Python_Beautifulsoup - Fatal编程技术网

Python 美丽的汤在错误上循环

Python 美丽的汤在错误上循环,python,beautifulsoup,Python,Beautifulsoup,目前正试图通过Beautifulsoup在NumberO.com上搜索,以提取我数据框架中约200个城市的生活成本 我有以下代码,但有一个问题,他们在url报告不同。例如,有些仅包含城市名称,而另一些则以连字符和州缩写结尾 还有一些其他问题,但如果出现错误,如何重新配置下面的代码以跳转到另一个选项: cofl_list = [] def cost_living(cit): cit = str(cit) cit = cit.replace('St. Petersburg','S

目前正试图通过Beautifulsoup在NumberO.com上搜索,以提取我数据框架中约200个城市的生活成本

我有以下代码,但有一个问题,他们在url报告不同。例如,有些仅包含城市名称,而另一些则以连字符和州缩写结尾

还有一些其他问题,但如果出现错误,如何重新配置下面的代码以跳转到另一个选项:

cofl_list = []
def cost_living(cit):
    cit = str(cit)
    cit = cit.replace('St. Petersburg','Saint-Petersburg-FL')

    cit = cit.replace(' ','-')
    cit = cit.replace('St.','Saint')
    
    url = r.get(f'https://www.numbeo.com/cost-of-living/in/{cit}')
    soup = bs(url.content)
    cof = soup.find_all('span', attrs= {'class': 'emp_number'} )
    cof_rev = cof[1]
    cof_rev = str(cof_rev)
    cof_rev = cof_rev.replace('$','')
    cof_rev = cof_rev.replace('<span class="emp_number">','')
    cof_rev = cof_rev.replace('</span>','')
    cof_rev = float(cof_rev)

    cofl_list.append(cof_rev)

cofl\u列表=[]
def生活成本(cit):
cit=str(cit)
cit=cit.replace('St.Petersburg','Saint-Petersburg-FL')
cit=cit.replace(“”,“-”)
cit=cit.replace('St.,'Saint')
url=r.get(f'https://www.numbeo.com/cost-of-living/in/{cit}')
soup=bs(url.content)
cof=soup.find_all('span',attrs={'class':'emp_number'})
cof_rev=cof[1]
cof_rev=str(cof_rev)
cof_rev=cof_rev.替换(“$”,“)
cof_rev=cof_rev.替换(“”,“”)
cof_rev=cof_rev.替换(“”,“”)
cof_rev=浮动(cof_rev)
cofl_列表追加(cof_修订版)
例如:

def my_func():
    try:
        # execute a block of script

    except:
        # if an error occurs in the block under try it gets catched here so You can execute something here
        continue


但是,如果导致错误的部分后面的块中有代码,则不会执行该代码

您可以尝试使用
try:except:
statementsThanks。你能不能在except下再尝试一次/except?@sobcza11据我所知,这不应该是个问题,你也可以排除多个错误,并以不同的方式处理它们,比如
除了indexer
,然后用相同的缩进做另一个,例如
除了ValueError
不需要,只是为了向你展示。