【发布时间】:2020-02-27 10:46:25
【问题描述】:
我正在尝试使用requests 和lxml.htmlpackages 为给定网页构建网络爬虫。
当我尝试迭代它的页面时,似乎我总是得到第一页的 html。理想情况下,我想检索每个页面的主表的内容并将其存储在 pandas df 中。
我的代码失败的任何建议?我正在使用 python 3.7.4 和 Ubuntu 操作系统
import requests
import lxml.html as lh
import pandas as pd
base_url = "https://etfdb.com/etfs/asset-class/#etfs&sort_name=assets_under_management&sort_order=desc&page="
n_pages = 15
data = []
for i in range(1,n_pages+1):
url = base_url+str(i)
page = requests.get(url)
doc = lh.fromstring(page.content)
# Retrieve all tr_like elements (table rows)
tr_elements = doc.xpath('//tr')
#Create a columns vector to create our df
col = list(filter(None,tr_elements[0].text_content().split("\n")))
#Iterate over the rows of the table
for j in range(1,len(tr_elements)-1):
row = tr_elements[j]
#Since there are multiple tables in the webpage, make sure
#we are retrieving the rows of the correct one
if len(row)==len(col):
data.append([value.text_content() for value in row.iterchildren()])
else:
print("Ignoring data")
df = pd.DataFrame(data,columns=col)
【问题讨论】:
-
我没有看到您正在使用 page 或 doc 做任何事情。你能包括其余的代码吗?
-
就像@Dinac23 说的。如果你想获得 another 页面,你需要制作 another
requests.get你没有这样做。顺便说一句,您的代码不可重现,请提供其余部分。 -
@Dinac23 我刚刚更新了代码,我错过了一部分。我在for循环中动态更改url,不应该更新“page”和“doc”变量吗?
-
@eusoubrasileiro 我刚刚更新了代码,我错过了一部分。我在for循环中动态更改url,不应该更新“page”和“doc”变量吗?
-
@AxelBorasinoDiBola 它接缝那个页面是问题所在。我很简单的
GET将无法使用它。尝试在Google chrome或Firefox上使用inspect 来查看您的浏览器正在生成的请求标头并从中工作。
标签: python html ubuntu web-scraping python-requests