Skip to main content
 首页 » 编程设计

python之从文本文件中复制数据,并将其插入到 URL 中

2024年09月07日7lyj

背景:

我正在构建一个从互联网上抓取天气数据并将其作为 GUI 的一部分显示给用户的程序。用户将输入他们的位置详细信息,特别是他们的邮政编码或邮政编码、城市或城镇、纬度和经度。该程序会将这四条信息存储到一个文本文件中,这样每次用户想要请求天气数据时都可以读取详细信息,而不必在每次请求时都输入这些详细信息。这个问题涉及的模块是urllib和BeautifulSoup。

import urllib.request 
from bs4 import BeautifulSoup 

问题:

我已经成功地将用户详细信息存储到一个文本文件中,并从中读取。插入数据的代码如下所示:

userPostcode = postcodeEntry.get() 
userCity     = cityEntry.get() 
userLat      = latitudeEntry.get() 
userLong     = longitudeEntry.get() 
file = open("LocationInfo.txt", 'w') 
file.write(str(userPostcode) + "\n") 
file.write(str(userCity) + "\n") 
file.write(str(userLat) + "\n") 
file.write(str(userLong)+ "\n") 
file.close() 

文本文件中的数据结构如下所示:

SK15 IJF 
SOME TOWN 
54.25 
-122.312 

读取文本文件的代码如下所示:

f=open('LocationInfo.txt') 
line=f.readlines() 
Post = line[0] 
Town = line[1] 
Lat  = line[2] 
Long = line[3] 
f.close() 

我将这些变量的值插入 URL 的方法是使用以下方法:

page_url = "https://www.metcheck.com/WEATHER/now_and_next.asp?  
zipcode=%s+%s&lat=%s&lon=%s" % (Post, Town, Lat, Long) 
soup = BeautifulSoup(urllib.request.urlopen(page_url), "lxml") 

*请注意,在实际程序中,url 全部位于一行。

错误:

我收到的错误是:

Exception in Tkinter callback 
Traceback (most recent call last): 
Python\Python36-32\lib\http\client.py", line 279, in _read_status 
raise BadStatusLine(line) 
http.client.BadStatusLine: <html> 

只有当我尝试使用分配给文本文件中数据的变量名称,并尝试使用 % 方法将它们插入 URL 时,才会出现此错误。当我直接将值输入 URL 字符串而不是使用变量名称时,会出现预期的结果。因此,我有理由相信问题出在变量本身和值上,而不是有效的实际数据。

请您参考如下方法:

要解决您的换行问题,请考虑将信息也存储为 JSON 文件。这将使解析更容易,这就是它的设计目的!如果您希望将来这样做,它还允许您向程序添加功能。

这与您的问题关系不大,OP。但不建议从网页中抓取 HTML 数据。我不知道你是如何解析你的数据的,但如果网站的设计发生变化,它可能会伤害你的解析器。

更好的方法是寻找 API。哪个 metcheck 有。 更多信息 here .更准确地说,this (在 JSON URL 下查看)。

import json 
 
json_data = "" 
with open("test.json") as json_file: 
    json_data = json.load(json_file) 
 
print(json_data["zipcode"]) # prints the zip code. 

您网站的示例:

import requests 
import json 
json_data = requests.get("http://ws1.metcheck.com/ENGINE/v9_0/json.asp?lat=51.8&lon=-0.1&lid=60357&Fc=No").text 
first_day = json.loads(json_data)["metcheckData"]["forecastLocation"]["forecast"][0] 
print(first_day["weekday"]) # print the first day of the first forecast. 
print(first_day["temperature"]) # print the temperature of the first day.