我從網站上用python和BS4抓取一系列鏈接,但是我需要清理它們,所以我只能得到字符串中的URL。從python中的字符串中除去一切,但是除去網址
的鏈接我得到這個樣子:
的javascript:changeChannel( 'http://some-server.com/with1234init.also',20);
,我需要它看起來像這樣
我從網站上用python和BS4抓取一系列鏈接,但是我需要清理它們,所以我只能得到字符串中的URL。從python中的字符串中除去一切,但是除去網址
的鏈接我得到這個樣子:
的javascript:changeChannel( 'http://some-server.com/with1234init.also',20);
,我需要它看起來像這樣
好了,如果所有的鏈接都是這樣的一個你可以用一個非常簡單的方法做到這一點:
s.split("'")[1]
例如:
>>>s="javascript:changeChannel('http://some-server.com/with1234init.also', 20);"
>>>s.split("'")
['javascript:changeChannel(',
'http://some-server.com/with1234init.also',
', 20);']
是真的,我準備發佈這個,但是它並沒有給你一些東西也許,你可以做到這一點,然後_then_用正則表達式搜索來確定索引值 –
那麼,如果所有的字符串格式化相同,這可能適用於每個人。 ? –
例如,這條線上只有兩個單引號。實質上,這種解決方案只適用於這個問題,但並不能解決問題。 –
str = javascript:changeChannel('http://some-server.com/with1234init.also', 20);
formattedtext ="http://" + str.split("http://")[1].split(',')[0].strip("'")
一個相當健壯的方法是把你的大塊文本和URL匹配的正則表達式模式進行搜索。
參見:
Python regular expression again - match url
其在此鏈接到:http://daringfireball.net/2010/07/improved_regex_for_matching_urls
Extracting URL link using regular expression re - string matching - Python
使用正則表達式...
import re
re.search(pattern, text)
... or
re.findall(pattern, text)
完整的例子...
>>> p = re.compile(r'(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?«»「」‘’]))')
or
>>> p = re.compile('(?i)\\b((?:https?://|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:\\\'".,<>?\xc2\xab\xc2\xbb\xe2\x80\x9c\xe2\x80\x9d\xe2\x80\x98\xe2\x80\x99]))')
>>> m = p.search("javascript:changeChannel('http://some-server.com/with1234init.also', 20);")
>>> m.group()
'http://some-server.com/with1234init.also'
使用的模式是從above link
注意該網頁的網址版本使用r
前綴和接近尾聲的逃脫'
報價在第一種模式中。使用
re.compile緩存中的正則表達式模式
你有什麼企圖? – spiehr
所有字符串都是完全相同的格式,還是HTML中存在可能導致簡單規則失敗的邊界情況? – jozxyqk
我忘了提及我抓取的所有鏈接都不一樣。他們都以javascript:changeChannel開頭('部分,但網址不同,最後一個結尾'在所有鏈接中也不相同 – user3332151