Skip to main content
 首页 » 编程设计

python之使用 Python 进行网页抓取(初学者)

2024年10月17日11txw1958

我正在做“使用 Python 自动化无聊任务”一书中的网络抓取教程的第一个示例。该项目包括在命令行中键入搜索词,然后让我的计算机自动打开浏览器,并在新选项卡中显示所有热门搜索结果

它提到我需要找到

<h3 class="r">  

来自页面源的元素,它是每个搜索结果的链接。 r 类仅用于搜索结果链接。

但问题是我无法在任何地方找到它,即使使用 Chrome Devtools。任何关于它在哪里的帮助将不胜感激。

注:仅供引用,这是书中所见的完整程序。

# lucky.py - Opens several Google search results. 
 
import requests, sys, webbrowser, bs4 
 
print('Googling..') # display text while downloading the Google page 
res= requests.get('http://google.com/search?q=' + ' '.join(sys.argv[1:])) 
res.raise_for_status() 
 
#Retrieve top searh result links. 
soup = bs4.BeautifulSoup(res.text) 
 
#Open a browser tab for each result. 
linkElems = soup.select('.r a') 
numOpen = min(5,len(linkElems)) 
for i in range(numOpen): 
    webbrowser.open('http://google.com' + linkElems[i].get('href')) 

请您参考如下方法:

这对你有用:

>>> import requests 
>>> from lxml import html 
>>> r = requests.get("https://www.google.co.uk/search?q=how+to+do+web+scraping&num=10") 
>>> source = html.fromstring((r.text).encode('utf-8')) 
>>> links = source.xpath('//h3[@class="r"]//a//@href') 
>>> for link in links: 
        print link.replace("/url?q=","").split("&sa=")[0] 

输出:

http://newcoder.io/scrape/intro/ 
https://www.analyticsvidhya.com/blog/2015/10/beginner-guide-web-scraping-beautiful-soup-python/ 
http://docs.python-guide.org/en/latest/scenarios/scrape/ 
http://webscraper.io/ 
https://blog.hartleybrody.com/web-scraping/ 
https://first-web-scraper.readthedocs.io/ 
https://www.youtube.com/watch%3Fv%3DE7wB__M9fdw 
http://www.gregreda.com/2013/03/03/web-scraping-101-with-python/ 
http://analystcave.com/web-scraping-tutorial/ 
https://en.wikipedia.org/wiki/Web_scraping 

注意:我使用的是 Python 2.7.X,对于 Python 3.X,您只需像这样包围打印输出 print (link.replace ("/url?q=","").split("&sa=")[0])