Python 文件请求中的 URL

Python URLs in file Requests

我的 Python 脚本有问题,我想从每个网站抓取相同的内容。我有一个包含很多 URL 的文件,我希望 Python 遍历它们以将它们放入 requests.get(url) 对象中。之后我将输出写入名为 'somefile.txt'.

的文件

我必须使用以下 Python 脚本(版本 2.7 - Windows 8):

from lxml import html
import requests

urls = ('URL1',
'URL2',
'URL3'
    )

for url in urls:
    page = requests.get(url)


tree = html.fromstring(page.text)

visitors = tree.xpath('//b["no-visitors"]/text()')

print 'Visitors: ', visitors

f = open('somefile.txt', 'a')
    print >> f, 'Visitors:', visitors  # or f.write('...\n')
    f.close() 

如您所见,脚本中是否没有包含带有 URL 的文件。我尝试了很多教程但都失败了。文件名将是 'urllist.txt'。在当前脚本中,我只从 URL3 获取数据 - 在理想情况下,我想从 urllist.txt.

获取所有数据

尝试读取文本文件:

with open('urllist.txt', 'r') as f: #text file containing the URLS
     for url in f:
     page = requests.get(url)

您需要从您的行中删除换行符:

with open('urllist.txt', 'r') as f: #text file containing the URLS
     for url in f:
         page = requests.get(url.strip())

str.strip() 调用从行中删除所有空格(包括制表符、换行符和回车 returns)。

请务必在循环中处理 page ;如果你 运行 你的代码在循环外提取数据,你将得到的是你加载的最后一个响应中的数据。您也可以在 with 语句中只打开一次输出文件,以便 Python 再次关闭它:

with open('urllist.txt', 'r') as urls, open('somefile.txt', 'a') as output:
     for url in urls:
         page = requests.get(url.strip())

         tree = html.fromstring(page.content)
         visitors = tree.xpath('//b["no-visitors"]/text()')
         print 'Visitors: ', visitors
         print >> output, 'Visitors:', visitors

您应该将每个页面保存在一个单独的变量中,或者在 url 列表的循环中执行所有计算。

根据您的代码,当您的页面解析发生时,它将只包含最后一页获取的数据,因为您在每次迭代中覆盖了 page 变量。

像下面这样的东西应该附加所有页面的信息。

for url in urls:
    page = requests.get(url)


    tree = html.fromstring(page.text)

    visitors = tree.xpath('//b["no-visitors"]/text()')

    print 'Visitors: ', visitors

    f = open('somefile.txt', 'a')
        print >> f, 'Visitors:', visitors  # or f.write('...\n')
        f.close()