我如何才能使这个代码(谷歌街景)工作?我每次都会收到403条禁止的消息,即使我设置了一个用户代理

2024-04-29 04:34:46 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我正在尝试一个下载谷歌街景图片的程序。地址位于.txt文件中。每次我尝试运行代码时,就会出现HTTP错误403:Forbidden。在我的实际代码中,我当然使用我的GoogleDeveloperAPI和正确的文件路径

我试图设置一个用户代理,但它就是不起作用。谁能帮帮我,我该怎么办?我如何在这段代码中实现它

# import os and urllib modules
# os for file path creation
# urllib for accessing web content
import urllib
import os
import requests

# this is the first part of the streetview, url up to the address, this url will return a 600x600px image

pre = "https://maps.googleapis.com/maps/api/streetview?size=600x600&location="

# this is the second part of the streetview url, the text variable below, includes the path to a text file containing one address per line
# the addresses in this text file will complete the URL needed to return a streetview image and provide the filename of each streetview image

text = r"C:\Users\.............

# this is the third part of the url, needed after the address
# this is my API key, please replace the one below with your own (google 'google streetview api key'), thanks!

suf = "&key=abcdertghjhrtrwhgrh"

# this is the directory that will store the streetview images
# this directory will be created if not present

dir = r"C:\Users\..........
headers = {'User-Agent': 'Chrome/75.0.3770.100 Safari/537.36',
    'From': 'asdasd@asd.com'
}
# checks if the dir variable (output path) above exists and creates it if it does not

if not os.path.exists(dir):
    os.makedirs(dir)

# opens the address list text file (from the 'text' variable defined above) in read mode ("r")
with open(text, "r") as text_file:
    # the variable 'lines' below creates a list of each address line in the source 'text' file
    lines = [line.rstrip('\n') for line in open(text)]
    print
    "THE CONTENTS OF THE TEXT FILE:\n" + str(lines)
    # start a loop through the 'lines' list
    for line in lines:
        # string clean-up to get rid of commas in the url and filename
        ln = line.replace(",", "")
        print
        "CLEANED UP ADDRESS LINE:\n" + ln
        # creates the url that will be passed to the url reader, this creates the full, valid, url that will return a google streetview image for each address in the address text file
        URL = pre + ln + suf
        response = requests.get(URL, headers = headers)
        "URL FOR STREETVIEW IMAGE:\n" + URL
        # creates the filename needed to save each address's streetview image locally
        filename = os.path.join(dir, ln + ".jpg")
        print
        "OUTPUT FILENAME:\n" + filename
        # you can run this up to this line in the python command line to see what each step does
        # final step, fetches and saves the streetview image for each address using the url created in the previous steps
        urllib.urlretrieve(URL, filename)

Tags: ofthetotextinimageurlfor