![](/img/trans.png)
[英]How can I loop scraping data for multiple pages in a website using python and beautifulsoup4
[英]How can I get frequently updated .php text from a website in Python using BeautifulSoup4?
我想創建一個自動腳本來從經常更新的網頁下載 a.php 文本文件。 我的程序使用請求來獲取網頁。
編碼:
import os, pathlib, subprocess,requests, time, sys
url = 'http://metar.vatsim.net/metar.php?id=all'
current_dir = pathlib.Path(__file__).parent
os.chdir(current_dir)
icao = sys.argv[1]
fp = requests.get(url)
mybytes = fp.read()
mystr = mybytes.decode("utf8")
fp.close()
dict = {}
fls = str.splitlines(mystr)
for x in range(len(fls)):
cur = str.split(fls[x])
dict[cur[0]] = " ".join(cur)
try:
print(dict[icao])
except:
print('INCORRECT FORMAT OR AIRPORT ID\n')
當我嘗試讀取 fp 時,它顯示錯誤:
mybytes = fp.read()
AttributeError: 'Response' object has no attribute 'read'
有沒有更好的方法來解決這個問題,我有點卡住了。
您正在尋找的是urllib.request
,而不是requests
。
也許這會起作用:
import urllib.request
fp = urllib.request.urlopen(url)
mybytes = fp.read()
mystr = mybytes.decode("utf8")
fp.close()
您絕對可以使用請求。 然后,您要提取.text
。
另外,不要以你正在做的方式覆蓋內置的dict
。
import requests
url = 'http://metar.vatsim.net/metar.php?id=all'
fp = requests.get(url)
mystr = fp.text
a_dict = {}
fls = str.splitlines(mystr)
for x in range(len(fls)):
cur = str.split(fls[x])
a_dict[cur[0]] = " ".join(cur)
try:
print(a_dict)
except:
print('INCORRECT FORMAT OR AIRPORT ID\n')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.