【发布时间】:2018-03-02 11:18:30
【问题描述】:
我正在尝试运行下面的代码以获取 URL 列表(在文件 out.txt 中)并使用 xpath 从该页面中提取文本内容。代码从 URL 中找到域,然后在我创建的同时具有域和 Xpath 的 json 文件中查找域。然后使用 xpath 来查找内容。
但是,现在如果我在循环之外运行代码,它可以正常工作(页面 = 200)。但如果我在循环内执行此操作,我将得到 page=404。
我确定这是循环的语法错误,可能非常简单。我做错了什么?
URLList = open("out.txt").readlines()
for item in URLList:
inputurl = item
print (inputurl)
type(inputurl)
#this takes a URL and finds the xpath - it uses an external
domainlookup.json that is manually created
# inputurl = input("PLEASE PROVIDE A URL FROM AN APPROVED DOMAIN: ")
t = urlparse(inputurl).netloc
domain = ('.'.join(t.split('.')[1:]))
with open('domainlookup.json') as json_data:
domainlookup = json.load(json_data)
for i in domainlookup:
if i['DOMAIN'] == domain:
xpath = (i['XPATH'])
#this requests the xpath from the URL and scrapes the text content
page = requests.get(inputurl)
tree = html.fromstring(page.content)
content = tree.xpath(xpath)
【问题讨论】:
标签: python-3.x list loops xpath