|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 jayinsky2005 于 2017-7-4 22:14 编辑
以下的web scraping代码中有一些地方想不到为何要这样编,求解答:
===========================================================
url_list = ['url1', 'url2', 'url3'...]
res=[] #placing res outside of loop -------------问题1: 为何这个要放在loop外头,而且为何下面又有另一个res = [i for i in res if i[0]!='']
for link in url_list:
r = requests.get(link)
r.encoding = 'utf-8'
html_content = r.text
soup = BeautifulSoup(html_content, 'lxml')
table = soup.find('table', class_='bigborder')
if not table:
continue
trs = table.find_all('tr')
if not trs:
continue #if trs are not found, then starting next iteration with other link
headers = trs[0]
headers_list=[]
for td in headers.find_all('td'):
headers_list.append(td.text)
headers_list+=['Season']
headers_list.insert(19,'pseudocol1')
headers_list.insert(20,'pseudocol2')
headers_list.insert(21,'pseudocol3')
row = []
season = '' ---------- 问题2: 这个的意义是什麽
for tr in trs[1:]:
if 'Season' in tr.text:
season = tr.text
else:
tds = tr.find_all('td')
for td in tds:
row.append(td.text.strip('\n').strip('\r').strip('\t').strip('"').strip())
row.append(season.strip())
res.append(row)
row=[] ------------问题3: 这个跟上面蓝色的row=[]不是又重覆了吗?
res = [i for i in res if i[0]!=''] #outside of loop -----------问题4: 这个我完全看不懂是要干甚麽
df=pd.DataFrame(res, columns=headers_list) #outside of loop
del df['pseudocol1'],df['pseudocol2'],df['pseudocol3']
|
|