如何从抓取Python中填充空记录?
我这里的问题是,我从列表中删除的一些元素没有心房纤支。当我尝试impar[7].find_all'td',{class':zentriert}[6]时,我在执行impar[7]时会得到它。find_all'td',{class':zentriert}[6].img.get'alt我得到一个错误 AttributeError:'NoneType'对象没有属性'get',但此代码适用于我的大多数记录。。。我是否可以跳过产生此错误的记录,或者用NaN或None填充该记录?将访问权包装在try:except AttributeError: 您还无缘无故地一遍又一遍地查询TDs;我也重构了它:如何从抓取Python中填充空记录?,python,web-scraping,beautifulsoup,request,Python,Web Scraping,Beautifulsoup,Request,我这里的问题是,我从列表中删除的一些元素没有心房纤支。当我尝试impar[7].find_all'td',{class':zentriert}[6]时,我在执行impar[7]时会得到它。find_all'td',{class':zentriert}[6].img.get'alt我得到一个错误 AttributeError:'NoneType'对象没有属性'get',但此代码适用于我的大多数记录。。。我是否可以跳过产生此错误的记录,或者用NaN或None填充该记录?将访问权包装在try:exce
headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'}
r = requests.get('https://www.transfermarkt.com.br/esporte-clube-bahia/kader/verein/10010/saison_id/2019/plus/1', headers=headers)
soup = BeautifulSoup(r.text, 'html.parser')
impar = soup.find('table',{'class':'items'}).find_all('tr',{'class':'odd'})
bahia = []
for jog in impar:
nome = jog.find_all('tr')[0].img.get('alt')
posicao = jog.find_all('td',{'class':"zentriert"})[0].get('title')
idade = jog.find_all('td',{'class':"zentriert"})[1].text
nacionalidade = jog.find_all('td',{'class':"zentriert"})[2].img.get('alt')
altura = jog.find_all('td',{'class':"zentriert"})[3].text[0:-2]
pe = jog.find_all('td',{'class':"zentriert"})[4].text
desde =jog.find_all('td',{'class':"zentriert"})[5].text
clube_anterior = jog.find_all('td',{'class':'zentriert'})[6].img.get('alt')
preco_pago = jog.find_all('td',{'class':"zentriert"})[6].get('title')
contrato = jog.find_all('td',{'class':"zentriert"})[7].text
valor = jog.find('td',{'class':"rechts hauptlink"}).text[0:-4]
bahia.append((nome,posicao,idade,nacionalidade,altura,pe,desde,clube_anterior,preco_pago,contrato,valor))
更清楚的是,在另一方面,当我执行impar[1]。查找所有'td',{'class':zentriert}[6]时,我得到了我可以应用impar[1]。查找所有'td',{'class':zentriert}[6]IMG。GET’ALT’并没有错误。请把你的额外评论移到你的Q的身体中,考虑编辑你的Q,这样你就可以告诉你最简单的故事,而不用边讨论边完成。祝你好运
for jog in impar:
nome = jog.find_all("tr")[0].img.get("alt")
tds = jog.find_all("td", {"class": "zentriert"})
posicao = tds[0].get("title")
idade = tds[1].text
nacionalidade = tds[2].img.get("alt")
altura = tds[3].text[0:-2]
pe = tds[4].text
desde = tds[5].text
try:
clube_anterior = tds[6].img.get("alt")
except AttributeError:
clube_anterior = None
preco_pago = tds[6].get("title")
contrato = tds[7].text
valor = jog.find("td", {"class": "rechts hauptlink"}).text[0:-4]
bahia.append(
(
nome,
posicao,
idade,
nacionalidade,
altura,
pe,
desde,
clube_anterior,
preco_pago,
contrato,
valor,
)
)