繁体   English   中英

Python Web 抓取用户输入?

[英]Python Web scraping with user input?

这是我第一次尝试 web 抓取。 我试图通过 state 找到汽油价格。 我做的第一个有效的代码是

url = "https://www.gasbuddy.com/usa/la"

    page = requests.get(url)

    soup = BeautifulSoup(page.content, 'html.parser')

    title = soup.find(id= "Nevada").get_text()
    price = soup.find("div", class_="col-sm-2 col-xs-3 text-right").get_text()
    print(price)
    print(title)

现在我想做它,以便用户可以输入 state。 在第一个程序中,我刚刚选择了一个 state 并这样写

title = soup.find(id= "Nevada").get_text()

我将如何做到这一点,这样就可以了

State = input("Input Your State ")
title = soup.find(id= State ).get_text()

该网站受 cloudflare 保护。 这就是为什么您不能使用普通请求来抓取它的原因。 您可以使用 cloudcraper 模块来抓取它。 安装它: pip install cloudscraper

代码:

import cloudscraper
scraper = cloudscraper.create_scraper()

url = "https://www.gasbuddy.com/usa/la"

page = scraper.get(url)

soup = BeautifulSoup(page.content, 'html.parser')

state = input("Input Your State ").strip()
title = soup.find(id= state ).get_text()

price = soup.find("div", class_="col-sm-2 col-xs-3 text-right").get_text()
print(price)
print(title)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM