网页抓取python
我一直在尝试使用这段代码来提取url,但我无法获得以html显示的google maps url。当我尝试在此段中查找url时,它返回“None”网页抓取python,python,html,web-scraping,html-parsing,beautifulsoup,Python,Html,Web Scraping,Html Parsing,Beautifulsoup,我一直在尝试使用这段代码来提取url,但我无法获得以html显示的google maps url。当我尝试在此段中查找url时,它返回“None” import urllib from bs4 import BeautifulSoup from urllib.parse import urlparse from urllib.request import urlopen url="http://www.example.com" html=urlopen(url) soup=BeautifulSo
import urllib
from bs4 import BeautifulSoup
from urllib.parse import urlparse
from urllib.request import urlopen
url="http://www.example.com"
html=urlopen(url)
soup=BeautifulSoup(html)
for tag in soup.findAll('a',href=True):
print(tag['href'])
<div class="map_container">
<div id="map_canvas" style="width: 100%; height: 450px; margin-top: 10px; position: relative; background-color: rgb(229, 227, 223); overflow: hidden; -webkit- transform: translateZ(0px);">
<div class="gm-style" style="position: absolute; left: 0px; top: 0px; overflow: hidden; width: 100%; height: 100%; z-index: 0;">
<div style="position: absolute; left: 0px; top: 0px; overflow: hidden; width: 100%; height: 100%; z-index: 0;">...</div>
<div style="margin-left: 5px; margin-right: 5px; z-index: 1000000; position: absolute; left: 0px; bottom: 0px;">
<a target="_blank" href="http://maps.google.com/mapsll=28.535959,77.146119&z=14&t=m&hl=en&gl=US&mapclient=apiv3" title="Click to see this area on Google Maps" style="position: static; overflow: visible; float: none; display: inline;">
<div style="width: 62px; height: 26px; cursor: pointer;">...</div>
</a>
</div>
</div>
</div>
</div>
导入urllib
从bs4导入BeautifulSoup
从urllib.parse导入urlparse
从urllib.request导入urlopen
url=”http://www.example.com"
html=urlopen(url)
soup=BeautifulSoup(html)
对于soup.findAll('a',href=True)中的标记:
打印(标签['href'])
...
这里的问题是,这个maps.google.com
链接是使用javascript构建的div
的一部分urllib
(或urllib2
)加载带有空map\u画布的页面
div:
>>> import urllib2
>>> from bs4 import BeautifulSoup
>>> url = "http://www.zomato.com/ncr/monkey-bar-vasant-kunj-delhi/maps#tabtop"
>>> doc = BeautifulSoup(urllib2.urlopen(url))
>>> print doc.find('div', id='map_canvas')
<div id="map_canvas" style="width:100%; height:450px; margin-top: 10px;"></div>
在呈现您试图刮取的页面时,可能需要Javascript。在这种情况下,
urllib
请求将不会完全按照您在浏览器中看到的方式呈现该页面。为此,您需要使用Selenium
。将soup=beautifulsop(html)
更改为soup=beautifulsop(html,'html.parser')
是否有帮助?您如何尝试查找标记属性?在我看来它就在那里。。
标记,对吗?@alecxe将soup=BeautifulSoup(html)更改为soup=BeautifulSoup(html,'html.parser')没有帮助。@aIKid是的,我正在使用
标记可以更快吗?打开firefox并加载会花费太多时间,我有一个要从中提取google地图url的页面列表。@user3612315您可以使用无头浏览器。看到和
>>> from selenium import webdriver
>>> browser = webdriver.Firefox()
>>> browser.get(url)
>>> link = browser.find_element_by_xpath('//div[@id="map_canvas"]//a')
>>> link.get_attribute('href')
u'http://maps.google.com/maps?ll=28.536562,77.147664&z=14&t=m&hl=en&gl=US&mapclient=apiv3'