![](/img/trans.png)
[英]how to match a string from a list of strings and ignoring regex special characters?
[英]How to match the strings with special characters using regex
我正在嘗試使用BS4抓取網站數據,但無法編寫確切的語句來獲取所需的鏈接。 我想獲取到應該位於的搜索資源的鏈接
<a href="www.speed.org">Speed Org</a>
我為此編寫的代碼是:
r = re.compile(r'^<a(.)*speed.org(.)*</a>$')
我希望代碼顯示:
<a href="www.speed.org">Speed Org</a>
但是它沒有提供適當的輸出。 任何人都可以解決此代碼。
編輯:
有人指出,表達本身是錯誤的。 正確的表達式應該是: r'^<a(.*)speed.org(.*)</a>$'
由於我使用的是BS4,因此使用湯更容易得到結果。
感謝大家的幫助。 :)
如果您已經在使用BeautifulSoup,請不要將HTML視為字符串。 讓BeautifulSoup解析它,然后使用BeautifulSoup.find_all
搜索您的元素:
import re
from bs4 import BeautifulSoup
soup = BeautifulSoup(your_html, 'lxml')
links = soup.find_all('a', href=re.compile('www\.speed\.org'))
href=re.compile('www\\.speed\\.org')
僅使用正則表達式來縮小指向href
屬性與正則表達式匹配的鏈接的范圍。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.