python - 从 BeautifulSoup 页面检索所有信息

标签 python selenium-webdriver web-scraping beautifulsoup web-crawler

我正在尝试抓取 OldNavy 网页上产品的 URL。然而,它只给出了产品列表的一部分,而不是整个列表(例如,当 URL 远远超过 8 个时,只给出 8 个)。我希望有人能帮忙找出问题所在。

from bs4 import BeautifulSoup
from selenium import webdriver
import html5lib
import platform
import urllib
import urllib2
import json


link = http://oldnavy.gap.com/browse/category.do?cid=1035712&sop=true
base_url = "http://www.oldnavy.com"

driver = webdriver.PhantomJS()
driver.get(link)
html = driver.page_source
soup = BeautifulSoup(html, "html5lib")
bigDiv = soup.findAll("div", class_="sp_sm spacing_small")
for div in bigDiv:
  links = div.findAll("a")
  for i in links:
    j = j + 1
    productUrl = base_url + i["href"]
    print productUrl

最佳答案

此页面使用 JavaScript 加载元素,但仅当您向下滚动页面时才会加载。

它被称为“延迟加载”

您也必须滚动页面。

from selenium import webdriver
from bs4 import BeautifulSoup
import time

link = "http://oldnavy.gap.com/browse/category.do?cid=1035712&sop=true"
base_url = "http://www.oldnavy.com"

driver = webdriver.PhantomJS()
driver.get(link)

# ---

# scrolling

lastHeight = driver.execute_script("return document.body.scrollHeight")
#print(lastHeight)

pause = 0.5
while True:
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    time.sleep(pause)
    newHeight = driver.execute_script("return document.body.scrollHeight")
    if newHeight == lastHeight:
        break
    lastHeight = newHeight
    #print(lastHeight)

# ---

html = driver.page_source
soup = BeautifulSoup(html, "html5lib")

#driver.find_element_by_class_name

divs = soup.find_all("div", class_="sp_sm spacing_small")
for div in divs:
    links = div.find_all("a")
    for link in links:
    print base_url + link["href"]

想法:https://stackoverflow.com/a/28928684/1832058

关于python - 从 BeautifulSoup 页面检索所有信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40777864/

相关文章:

python - 将 %r 与元组一起使用时出错

ruby - 如何从隐藏元素中提取数据代码属性

python - unDetected_chromedriver 运行缓慢,有建议吗?

python:从列表中输出数据

python - 如何使用 pandas/matplotlib 绘制/管理 2 列分类数据?

selenium-webdriver - 如何在 Protractor 中模块化 Jasmine Reports 的 XML 报告

python - 如何使用 python beautiful soup 从下面的 HTML 中获取标签和 ID 信息

go - 如何在 Go 中加入 URL?

python - 在 Python 中打开文件时使用超时来防止死锁?

javascript - 如何清除文本输入?