首页 > 解决方案 > 如何使用 Python 请求更改我的当前位置?

问题描述

我正在尝试抓取亚马逊新加坡的卖家数量。为此,我使用了连接到新加坡服务器的 VPN 服务。但是我不想再使用它了,因为它的免费使用时间已过。我不想使用 VPN,而是想使用requests库更改我的位置。

这是我的代码:

# Set asin, link and headers
asin = XXXXXXXXXX
link = 'https://www.amazon.sg/dp/' + str(asin)

# Headers
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'}

# Set requests object
res = requests.get(link, params = {"format": "json"}, headers = headers)

# Create soup object
soup_data = BeautifulSoup(res.text, 'html.parser')
print(soup_data)

当我运行这段代码时,亚马逊看到我在土耳其(这是我当前的位置)。而且我看不到有多少人在销售该产品,因为亚马逊在土耳其看到了我。我想将我的位置更改为新加坡。如何使用requests库或更改来做到这一点headers

亚马逊有GET更改位置的参数吗?如:

www.amazon.sg/dp/ASIN_NUMBER?LOCATION=SINGAPORE

希望大家明白我的意思。

标签: pythonarraysstringpython-requestsgeolocation

解决方案


亚马逊可能正在使用您的 IP 来确定您的位置。您可以尝试使用一些公开可用的代理:

def main():

    import requests

    url = "https://d.pub.network/init"

    for address in ("http://45.77.151.33:8080", "http://136.244.83.131:8080"):
        proxies = {
            "https": address
        }
        
        response = requests.get(url, proxies=proxies)
        content = response.json()

        city = content["location"]["cityName"]
        country = content["location"]["countryCode"]

        print("I think you are in {}, {}".format(city, country))
    
    return 0


if __name__ == "__main__":
    import sys
    sys.exit(main())

输出:

I think you are in Piscataway, US
I think you are in Frankfurt am Main, DE
>>> 

推荐阅读