【问题标题】:Extracting a specific substring from a specific hyper-reference using Python使用 Python 从特定的超引用中提取特定的子字符串
【发布时间】:2017-12-29 12:17:19
【问题描述】:

我是 Python 新手,在我第二次尝试一个项目时,我想从 url 上的超引用中提取一个子字符串——具体来说,一个标识号。

例如,this url 是我的搜索查询的结果,给出了超引用 http://www.chessgames.com/perl/chessgame?gid=1012809。从中我想提取识别号“1012809”并将其附加以导航到 url http://www.chessgames.com/perl/chessgame?gid=1012809,之后我计划在 url http://www.chessgames.com/pgn/alekhine_naegeli_1932.pgn?gid=1012809 处下载文件。但我目前被困在这后面几步,因为我想不出提取标识符的方法。

这是我的 MWE:

from bs4 import BeautifulSoup
url = 'http://www.chessgames.com/perl/chess.pl?yearcomp=exactly&year=1932&playercomp=white&pid=&player=Alekhine&pid2=&player2=Naegeli&movescomp=exactly&moves=&opening=&eco=&result=1%2F2-1%2F2'
page = urllib2.urlopen(url)
soup = BeautifulSoup(page, 'html.parser')
import re
y = str(soup)
x = re.findall("gid=[0-9]+",y)
print x
z = re.sub("gid=", "", x(1))  #At this point, things have completely broken down...

【问题讨论】:

  • 顺便说一句,beautifulsoup 有什么用?
  • re.findall() 返回一个列表 x ,您正试图像函数 x(1) 一样调用列表,这是错误的,您可以通过编写 x[0] 获得第一个值
  • 谢谢大家。我已经对你的答案投了赞成票,但它们不会显示,因为我还没有建立 >15 的声望。
  • 如果任何一个答案都能奏效,请务必选择它作为您选择的答案。

标签: python regex beautifulsoup


【解决方案1】:

正如 Albin Paul 评论的那样,re.findall 返回一个列表,您需要从中提取元素。对了,这里不需要BeautifulSoup,使用urllib2.urlopen(url).read()获取内容的字符串,这里也不需要re.sub,一个正则表达式(?:gid=)([0-9]+)就够了。

import re
import urllib2
url = 'http://www.chessgames.com/perl/chess.pl?yearcomp=exactly&year=1932&playercomp=white&pid=&player=Alekhine&pid2=&player2=Naegeli&movescomp=exactly&moves=&opening=&eco=&result=1%2F2-1%2F2'

page = urllib2.urlopen(url).read()

result = re.findall(r"(?:gid=)([0-9]+)",page)

print(result[0])
#'1012809'

【讨论】:

    【解决方案2】:

    这里根本不需要正则表达式。 Css 选择器和字符串操作将引导您走向正确的方向。试试下面的脚本:

    import requests
    from bs4 import BeautifulSoup
    
    page_link = 'http://www.chessgames.com/perl/chess.pl?yearcomp=exactly&year=1932&playercomp=white&pid=&player=Alekhine&pid2=&player2=Naegeli&movescomp=exactly&moves=&opening=&eco=&result=1%2F2-1%2F2'
    soup = BeautifulSoup(requests.get(page_link).text, 'lxml')
    item_num = soup.select_one("[href*='gid=']")['href'].split("gid=")[1]
    print(item_num)
    

    输出:

    1012809
    

    【讨论】:

      猜你喜欢
      • 2021-11-08
      • 2017-12-04
      • 2019-05-18
      • 2020-08-20
      • 2019-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多