【问题标题】:Web scraping python网页抓取 python
【发布时间】:2014-05-07 22:48:53
【问题描述】:

我一直在尝试使用此代码来提取网址,但我无法获得以 html 显示的谷歌地图网址。当我尝试在此段中查找 url 时,它返回“无”。

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&amp;z=14&amp;t=m&amp;hl=en&amp;gl=US&amp;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>

【问题讨论】:

  • 在呈现您尝试抓取的页面时可能需要 Javascript。在这种情况下,urllib 请求不会完全按照您在浏览器中看到的那样呈现该页面。为此,您需要使用 Selenium
  • soup=BeautifulSoup(html) 更改为soup=BeautifulSoup(html, 'html.parser') 有帮助吗?
  • 您是如何尝试查找标签属性的?它看起来就在我身边。&lt;a&gt; 标签,对吧?
  • @alecxe 将 soup=BeautifulSoup(html) 更改为 soup=BeautifulSoup(html, 'html.parser') 没有帮助。
  • @aIKid 是的,我正在使用&lt;a&gt; 标签

标签: python html web-scraping html-parsing beautifulsoup


【解决方案1】:

这里的问题是这个maps.google.com 链接是divid="map_canvas" 的一部分,它是使用javascript 构造的。 urllib(或urllib2)使用空的map_canvas 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>

这意味着您无法使用您现在使用的工具轻松获取链接。

另一种解决方案是使用selenium

>>> 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'

【讨论】:

猜你喜欢
  • 2021-01-12
  • 2022-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-20
  • 2023-03-12
  • 2018-04-25
  • 2019-06-18
相关资源
最近更新 更多