2016-11-28 5 views
0

Ich möchte die Ausgabe von meinem soup.find.all ändern. In der Originalquelle haben wir diese:So subtrahieren Sie soup.find_all() in Python 3

<a href="/book/nfo/?id=4756888" class="ajax nfo"></a> 

mein soup.find_all:

href = [b.get('href') for b in soup.find_all('a', href=re.compile(r'.*\?id\=\d{4,8}'))] 

gibt mir dies:

/book/nfo/?id=4756888 

aber ich möchte dies:

http://127.0.0.1/book/download/?id=4756888 
+0

Ist dies die einzige URL/Buch/nfo/wo Sie wollen Ersetze NFO mit Download? – MYGz

+0

Wie viele andere URLs gibt es? – MYGz

+0

Ich habe viele andere von irgendetwas URL. –

Antwort

0

können Sie vorangehen http://127.0.0.1 vor und ersetzen "NFO" durch "Download" mit Pythons re() -Funktion.

re.sub(r'pattern_to_match',r'replacement_string', string) 

Sie können es wie folgt implementieren:

from bs4 import BeautifulSoup 
import re 

soup = BeautifulSoup("""<a href="/book/nfo/?id=4756888" class="ajax nfo"></a>""") 
c = ['http://127.0.0.1'+b.get('href') for b in soup.find_all('a', href=re.compile(r'.*\?id\=\d{4,8}'))] 
print([re.sub(r'nfo',r'download',q) for q in c ]) 

Ausgang:

['http://127.0.0.1/book/download/?id=4756888'] 
1

Sie die Eigenschaften eines Python string verwenden können, hinzufügen und ersetzen Teile vom/es:

a='/book/nfo/?id=4756888' 
b = 'http://127.0.0.1' + a.replace('nfo', 'download') 
print(b) 

was ergibt:

'http://127.0.0.1/book/download/?id=4756888' 

Es gibt keine Notwendigkeit regex hier zu verwenden.

+0

Sie haben Recht. Aber ich war mir sicher, dass er mehr URLs einbringen wird :) – MYGz

0

Sie können einen regulären Ausdruck zusammenstellen und in einer Liste Verständnis gelten wie folgt:

from bs4 import BeautifulSoup 
import re 

soup = BeautifulSoup('<a href="/book/nfo/?id=4756888" class="ajax nfo"></a>', 'html.parser') 
re_s = re.compile(r'(.*?\/)nfo(\/.*?)').sub 
hrefs = [re_s('http://127.0.0.1' + r'\1download\2', a.get('href')) for a in soup.find_all('a', href=re.compile(r'.*\?id\=\d{4,8}'))] 
print(hrefs) 

Geben Sie:

['http://127.0.0.1/book/download/?id=4756888'] 
Verwandte Themen