python - 从文本文件复制数据并将其插入 URL

标签 python python-3.x urllib

背景:

我正在构建一个程序,该程序从互联网上抓取天气数据,并将其作为 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.

关于python - 从文本文件复制数据并将其插入 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49470274/

相关文章:

python - 解析 DRF 请求主体 : TypeError the JSON object must be str, 而不是 'bytes'

python - BeautifulSoup 没有提取所有 html(自动删除页面的大部分 html)

python - urllib2:如何通过 AuthHandler 向 *initial* 请求添加 header 的正确方法?

python - 每当我重新启动系统并启动 GAE Launcher 时,Google App Engine 都会出错

python - PyQt5/PySide2 广告拦截

python - 设置默认单元格大小

python - 执行此命令 ps aux | 的时间超过一个小时awk '{ print $10"\t"$12 }'

python - 为什么字典不像 urllib post 中的字符串?

python - 在不创建对象的情况下使用python中类的属性

python - 验证 Pandas 数据框列