【发布时间】:2016-02-13 12:16:45
【问题描述】:
如何仅将 LINKS 列表作为输出? 我已经尝试过使用 beautifulsoup 和 selennium 的其他解决方案,但它们仍然给我的结果与我目前得到的结果非常相似,即链接的 href 和锚文本。我尝试按照一些较旧的答案建议使用 urlparse,但似乎该模块不再使用,我对整个事情感到困惑。这是我的代码,目前正在输出链接和锚文本,这不是我想要的:
import requests, re
from bs4 import BeautifulSoup
headers = {'User-agent':'Mozilla/5.0'}
page = requests.get('https://www.google.com/search?q=Tesla',headers=headers)
soup = BeautifulSoup(page.content,'lxml')
global serpUrls
serpUrls = []
links = soup.findAll('a')
for link in soup.find_all("a",href=re.compile("(?<=/url\?q=)(htt.*://.*)")):
#print(re.split(":(?=http)",link["href"].replace("/url?q=","")))
serpUrls.append(link)
print(serpUrls[0:2])
xmasRegex = re.compile(r"""((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|(([^\s()<>]+|(([^\s()<>]+)))*))+(?:(([^\s()<>]+|(([^\s()<>]+)))*)|[^\s`!()[]{};:'".,<>?«»“”‘’]))""", re.DOTALL)
mo = xmasRegex.findall('[<a href="/url?q=https://www.teslamotors.com/&sa=U&ved=0ahUKEwjvzrTyxvTKAhXHWRoKHUjlBxwQFggUMAA&usg=AFQjCNG1nvN_Z0knKTtEah3whTIObUAhcg"><b>Tesla</b> Motors | Premium Electric Vehicles</a>, <a class="_Zkb" href="/url?q=http://webcache.googleusercontent.com/search%3Fq%3Dcache:rzPQodkDKYYJ:https://www.teslamotors.com/%252BTesla%26gws_rd%3Dcr%26hl%3Des%26%26ct%3Dclnk&sa=U&ved=0ahUKEwjvzrTyxvTKAhXHWRoKHUjlBxwQIAgXMAA&usg=AFQjCNEZ40VWO_fFDjXH09GakUOgODNlHg">En caché</a>]')
print(mo)
我只想要“http://urloflink.com”,而不是整行代码。有什么办法可以做到这一点?谢谢!
输出如下所示:
[<a href="/url?q=https://www.teslamotors.com/&sa=U&ved=0ahUKEwjI39vl2_TKAhXFWxoKHRX-CFgQFggUMAA&usg=AFQjCNG1nvN_Z0knKTtEah3whTIObUAhcg"><b>Tesla</b> Motors | Premium Electric Vehicles</a>, <a class="_Zkb" href="/url?q=http://webcache.googleusercontent.com/search%3Fq%3Dcache:rzPQodkDKYYJ:https://www.teslamotors.com/%252BTesla%26gws_rd%3Dcr%26hl%3Des%26%26ct%3Dclnk&sa=U&ved=0ahUKEwjI39vl2_TKAhXFWxoKHRX-CFgQIAgXMAA&usg=AFQjCNEZ40VWO_fFDjXH09GakUOgODNlHg">En caché</a>]
[('https://www.teslamotors.com/&sa=U&ved=0ahUKEwjvzrTyxvTKAhXHWRoKHUjlBxwQFggUMAA&usg=AFQjCNG1nvN_Z0knKTtEah3whTIObUAhcg"', '', '', '', '', '', '', '', ''), ('http://webcache.googleusercontent.com/search%3Fq%3Dcache:rzPQodkDKYYJ:https://www.teslamotors.com/%252BTesla%26gws_rd%3Dcr%26hl%3Des%26%26ct%3Dclnk&sa=U&ved=0ahUKEwjvzrTyxvTKAhXHWRoKHUjlBxwQIAgXMAA&usg=AFQjCNEZ40VWO_fFDjXH09GakUOgODNlHg"', '', '', '', '', '', '', '', '')]
【问题讨论】:
-
我是新手,所以我使用的是我猜到的最好的解决方案,但我怀疑它不是,这就是我问的原因。我相信有更好的方法或一些模块可以更轻松地完成它。我尝试安装 GoogleScraper 模块,但由于某种原因,pycharm 和 pip 都无法在我的计算机上安装它。
-
我也试过这个,也没有得到我需要的东西:results = driver.find_elements_by_css_selector('div.g') link = results[0].find_element_by_tag_name("a") href = link.get_attribute("href")
-
你看过urllib吗?
-
我做过,但我在某处听说“以后不要使用 URLlib。它比请求更复杂、更慢,所以使用请求”。这就是为什么我首先尝试了 Selenium/Request 路线。也许我错过了什么。
标签: python selenium hyperlink beautifulsoup