【问题标题】:Scraping the selected value from a dropdown menu从下拉菜单中抓取选定的值
【发布时间】:2019-07-16 05:49:07
【问题描述】:

我正在尝试从网页的下拉菜单中抓取所选值。如何将我的抓取范围缩小到正确的级别?

我已经在选择、选项、选项值和选择的“”上尝试了许多不同的组合与 find 和 find_all。

我想在这个 html 代码中获取选择后的值"">:

<select name="aar"><option value="2019/2020">2019/2020</option> 
     <option value="2018/2019" selected="">2018/2019</option><option 
     value="2017/2018">2017/2018</option><option 

我想要 2018/2019 作为我的结果

我当前的代码:

from bs4 import BeautifulSoup
for i in range(2018,2019):
    url='https://superstats.dk/program?aar={}%2F{}'.format(i,i+1)
    html_doc = requests.get(url)
    soup = BeautifulSoup(html_doc.content, "lxml")
    aar = soup.find_all("select")
    print(aar)

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    使用 Css 选择器获取 attr selected 的值

    from bs4 import BeautifulSoup
    for i in range(2018,2019):
        url='https://superstats.dk/program?aar={}%2F{}'.format(i,i+1)
        html_doc = requests.get(url)
        soup = BeautifulSoup(html_doc.content, "lxml")
        optionval = soup.select_one('option[selected]')['value']
        print(optionval)
    

    输出:

    2018/2019

    【讨论】:

      【解决方案2】:

      我为你编写了这个代码,你现在要做的就是每 9 个索引打印一个新行 你会在一个txt文件中从那个网站获得所有年份 别忘了安装我在代码中使用的库

      • 2019/2020
      • 2018/2019
      • 2017/2018
      • 2016/2017
      • 2015/2016
      • 等等

        1. 导入 urllib.request
        2. 从 bs4 导入 BeautifulSoup

      >

      url='https://superstats.dk/program?aar={}%2F{}'
      html_doc = urllib.request.urlopen(url)
      soup = BeautifulSoup(html_doc, "html.parser")
      
      show_select = str(soup.find_all("select"))
      file = open("test.txt", "w+") 
      
      for everything in show_select :
          file.write(str(everything))
      file.close()
      
      file = open("test.txt", "r")
      lines = file.readlines()
      number_of_lines = len(lines)
      
      placeholder = 0
      each_line = lines[placeholder]
      
      file2 = open("All numbers.txt", "w+")
      while placeholder < number_of_lines:
          for number in each_line:
              if number in "0123456789" :
                  file2.write(str(number))
                  placeholder += 1
              if number == "/":
                  file2.write(str(number))
                  placeholder += 1            
              else:
                  placeholder += 1
                  pass
      
          file2.close()
      

      【讨论】:

        猜你喜欢
        • 2019-05-23
        • 2019-10-31
        • 1970-01-01
        • 1970-01-01
        • 2013-07-13
        • 2020-04-20
        • 1970-01-01
        • 1970-01-01
        • 2021-09-13
        相关资源
        最近更新 更多