【问题标题】:BeautifulSoup/Regex: Find specific value from hrefBeautifulSoup/Regex:从 href 中查找特定值
【发布时间】:2018-07-06 07:26:29
【问题描述】:

使用下面的代码,并尝试在 href 末尾找到值。有没有办法提取href,并在BeutifulSoup/Regex 中找到page= 之后的值?

from bs4 import BeautifulSoup
import requests
import json
import re

request = requests.get('https://www.goodreads.com/quotes/tag/fun?page=1')
soup = BeautifulSoup(request.text, 'html.parser')

findNext = soup.find("a", class_="next_page")
print(findNext)

得到这个输出:

<a class="next_page" href="/quotes/tag/fun?page=2" rel="next">next »</a>

注意:要从上述或任何其他可能出现的数字中提取2

【问题讨论】:

  • 所以获取href 值,然后使用re 获取等号右侧的任何内容。
  • re.find('page=(\d+)',findNext['href'])
  • 你可以将其拆分成一个数组,然后选择数组中的最后一项!

标签: javascript python html regex beautifulsoup


【解决方案1】:

您可以使用regex查找页码:

from bs4 import BeautifulSoup
import re
request = requests.get('https://www.goodreads.com/quotes/tag/fun?page=1')
soup = BeautifulSoup(request.text, 'html.parser')
page_nums = re.findall('(?<=page\=)\d+', str(soup.find("a", class_="next_page")))[0]

输出:

2

【讨论】:

    【解决方案2】:
    from bs4 import BeautifulSoup
    import requests    
    
    request = requests.get('https://www.goodreads.com/quotes/tag/fun?page=1')
    soup = BeautifulSoup(request.text, 'html.parser')
    
    findNext = soup.find("a", class_="next_page").attrs['href'].split('page=')[1]
    print(findNext)
    #Result is 2
    

    【讨论】:

      【解决方案3】:

      使用正则表达式你可以做类似的事情,

          let url = "/quotes/tag/fun?page=2";
          let urlParam = url.substring(url.indexOf('?') + 1);
          let matches = urlParam.match(/=(.+)/);
          let username;
          if (matches) {
              username = matches[1];
          }
          return username;
      

      【讨论】:

      • 我喜欢固定的方法。此外,这是过去 15 分钟内我第二次看到有人使用letlet 的文档在哪里?首先我在 JavaScript 中看到它,现在我在 Python 中看到它。
      • @AlexanderDixon 看看这个letdocs
      【解决方案4】:

      var text = '<a class="next_page" href="/quotes/tag/fun?page=2" rel="next">next »</a>';
      var regex = /(?<=href=\")[^\?]+\?page=(\d+)(?=\")/
      var match = regex.exec(text);
      
      console.log("**href => " + match[0] + " **page => " + match[1]);

      Regex demo

      【讨论】:

        【解决方案5】:

        使用 JavaScript,您可以使用 URL 构造函数、.search 获取查询字符串参数、String.prototype.split() "=" 字符和 Array.prototype.pop()

        var param = new URL('https://www.goodreads.com/quotes/tag/fun?page=1')
                    .search.split("=").pop();
        
        console.log(param);

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-10-25
          • 1970-01-01
          • 1970-01-01
          • 2019-08-28
          • 1970-01-01
          • 1970-01-01
          • 2019-03-17
          相关资源
          最近更新 更多