【发布时间】:2016-02-02 03:49:09
【问题描述】:
我对正则表达式很陌生,所以我尝试自己解决了一段时间,但无法提出解决方案。 (我正在尝试使用 Python 2.7 来做到这一点)
我有一个来自帖子和笔记的 tumblr 链接列表。 他们看起来像
"http://TumblrUsername.tumblr.com/post/hello/notes/somemoresutff/464654"
我想要做的是只选择“http://TumblrUsername.tumblr.com/”部分并保留其余部分,以便我可以编译一个 tumblr 用户列表。
我的代码看起来像这样,但我的问题是如何选择我想要的...
import urllib
import requests
import lxml
from bs4 import BeautifulSoup
def find_notes():
file = open('output.txt', 'w')
f = requests.get('http://fullthrottleauto.tumblr.com/post/132323884114/treunenthibault-ferrari-599xx-evo-as-i-love')
soup = BeautifulSoup(f.text, "lxml")
for post_note in soup.find_all('a', href=True):
print post_note['href']
returnline = str(post_note['href'])
if '.tumblr.com/' in returnline:
## I need to do some thing here to extract "only the http://username.tumblr.com/"
file.write(returnline + '\n')
find_notes()
【问题讨论】:
-
你试过的代码在哪里?
-
感谢您的回复。目前没有具体的代码。让我发布我目前所拥有的。
-
所以here是文档,看看
.*部分,.+?部分和re.findall()部分,然后在你在这里提问之前尝试一下。 -
result = re.findall("http://TumblrUsername.tumblr.com", subject, re.IGNORECASE) -
@SIslam 我认为
TumblrUsername在这里不固定,它是一个用户名。所以也许re.findall(r'http://.+?\.tumblr\.com', string)。或者只是提取用户名部分:re.findall(r'http://(.+?)\.tumblr\.com', string).
标签: python regex hyperlink tumblr