lxml 没有更新网页
lxml not getting updated webpage
此处为简单脚本,我只是尝试每 15 分钟从网页中获取健身房的人数,并将结果保存在文本文件中。但是,脚本输出的结果是我第一次 运行 它 (39),而不是更新后的数字 93(可以通过刷新网页看到)。任何想法为什么会这样?请注意,我将睡眠时间设置为 10 秒,以防你想 运行 自己。
from lxml import html
import time
import requests
x = 'x'
while x == x:
time.sleep(10)
page = requests.get('http://www.puregym.com/gyms/holborn/whats-happening')
string = html.fromstring(page.content)
people = string.xpath('normalize-space(//span[@class="people-number"]/text()[last()])')
print people
#printing it for debug purposes
f = open("people.txt","w")
f.write(people)
f.write("\n")
干杯
你不是在每次循环后关闭 people.txt
文件,最好使用 Python 的 with
函数来执行此操作,如下所示:
from lxml import html
import time
import requests
x = 'x'
while x == 'x':
time.sleep(10)
page = requests.get('http://www.puregym.com/gyms/holborn/whats-happening')
string = html.fromstring(page.content)
people = string.xpath('normalize-space(//span[@class="people-number"]/text()[last()])')
print people
#printing it for debug purposes
with open("people.txt", "w") as f:
f.write('{}\n'.format(people))
如果您想保留所有条目的日志,则需要将 with 语句移到 while 循环之外。另外我认为你的意思是 while x == 'x'
。目前该网站正在显示 39
,在 people.txt
.
中可以看到
此处为简单脚本,我只是尝试每 15 分钟从网页中获取健身房的人数,并将结果保存在文本文件中。但是,脚本输出的结果是我第一次 运行 它 (39),而不是更新后的数字 93(可以通过刷新网页看到)。任何想法为什么会这样?请注意,我将睡眠时间设置为 10 秒,以防你想 运行 自己。
from lxml import html
import time
import requests
x = 'x'
while x == x:
time.sleep(10)
page = requests.get('http://www.puregym.com/gyms/holborn/whats-happening')
string = html.fromstring(page.content)
people = string.xpath('normalize-space(//span[@class="people-number"]/text()[last()])')
print people
#printing it for debug purposes
f = open("people.txt","w")
f.write(people)
f.write("\n")
干杯
你不是在每次循环后关闭 people.txt
文件,最好使用 Python 的 with
函数来执行此操作,如下所示:
from lxml import html
import time
import requests
x = 'x'
while x == 'x':
time.sleep(10)
page = requests.get('http://www.puregym.com/gyms/holborn/whats-happening')
string = html.fromstring(page.content)
people = string.xpath('normalize-space(//span[@class="people-number"]/text()[last()])')
print people
#printing it for debug purposes
with open("people.txt", "w") as f:
f.write('{}\n'.format(people))
如果您想保留所有条目的日志,则需要将 with 语句移到 while 循环之外。另外我认为你的意思是 while x == 'x'
。目前该网站正在显示 39
,在 people.txt
.