【发布时间】: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