我創(chuàng)建了一個代碼來從網(wǎng)站中提取電子郵件:import requestsfrom bs4 import BeautifulSoupimport reurl = ""s = requests.Session()r = s.get(url, headers={"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36"})soup = BeautifulSoup(r.content, 'html.parser')content = soup.get_text()emails_match = re.findall(r'[\w\.-]+@[\w\.-]+', content)它工作正常,但有時會從其他元素返回包含其他文本的電子郵件。print(email_match)['743-2538info@alliedsinterings.com']我只想獲取電子郵件地址(沒有來自其他 html 元素的任何文本)當我嘗試另一個正則表達式時,它返回相同的內(nèi)容,例如:r'([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9_-]+){0,}'
1 回答

胡說叔叔
TA貢獻1804條經(jīng)驗 獲得超8個贊
使用.strings而不是.text
import re
email = re.compile(r'([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9_-]+){0,}')
[x for x in soup.strings if email.search(x).group()]
['info@alliedsinterings.com']
添加回答
舉報
0/150
提交
取消