【问题标题】:Unable to scrape the links of different albums from script tags using requests?无法使用请求从脚本标签中抓取不同专辑的链接?
【发布时间】:2019-12-05 04:25:00
【问题描述】:

我用 python 和 selenium 创建了一个脚本来从网页中获取不同相册的链接。我的脚本完美地解析了它们。

由于相册是公开的,因此无需登录。

现在,我希望使用requestsre 模块做同样的事情,因为我可以在页面源中看到不同专辑的名称。但是,大多数脚本标签是相同的,所以我无法将包含所需网址的所需部分挖出到不同的专辑。

Website link

使用有效的硒:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

url = 'https://www.facebook.com/pg/bloo88/photos/?tab=albums'

def get_links(link):
    driver.get(link)
    items = sorted(set([item.get_attribute("href") for item in wait.until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "[role='presentation'] > a")))]))
    return items 

if __name__ == '__main__':
    with webdriver.Chrome() as driver:
        wait = WebDriverWait(driver,10)
        for elem in get_links(url):
            print(elem)

在使用requestsre 时,我得到了很多乱七八糟的东西,我无法从中挖掘出所需的链接,因为大多数脚本标签都是相似的:

import re
import json
import requests

url = 'https://www.facebook.com/pg/bloo88/photos/?tab=albums'

res = requests.get(url,headers={"User-Agent":"Mozilla/5.0"}).text
data = re.findall(r'adp_PagePhotosTabAlbums[^,]+(.*?)();</script>', res)[0]
print(data)

如何使用请求抓取不同相册的链接?

【问题讨论】:

标签: python regex python-3.x web-scraping


【解决方案1】:

如果你想匹配你的 selenium 输出,它给了我 4 个链接,你可以使用下面的正则表达式。 try it

import requests, re

base = 'https://www.facebook.com/pg/bloo88/photos/?tab=album&album_id='
p = re.compile(r'{"node":{"id":"(\d+)"')
r = requests.get('https://www.facebook.com/pg/bloo88/photos/?tab=albums')
links = [base + i for i in p.findall(r.text)]

【讨论】:

  • 结果非常完美!!你能告诉我如何获得其余的链接吗?非常感谢。
  • 我不认为它们都出现在响应中。我认为你需要 selenium 和一个缓慢的滚动来抓取所有内容。
猜你喜欢
  • 2019-12-06
  • 1970-01-01
  • 2021-01-10
  • 2021-07-11
  • 2020-04-05
  • 1970-01-01
  • 2020-12-25
  • 2021-04-26
  • 1970-01-01
相关资源
最近更新 更多