【问题标题】:Looping through strings in a list遍历列表中的字符串
【发布时间】: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


    【解决方案1】:

    您会发现使用此代码的代码有什么问题:

    URLList = open("out.txt").readlines()
    for item in URLList:
        inputurl = item
        print("[{0}]".format(inputurl) )
    

    从输出中可以看出,您没有从 URL 中删除 换行符,这就是 requests 以后无法加载它的原因。使用前只需strip()即可:

    inputurl = item.strip()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多