繁体   English   中英

无法从 Quora 网页上抓取许多问题

[英]Unable to scrape many questions from a Quora webpage

我正在学习 BeautifulSoup 并尝试抓取 Quora 页面上存在的不同问题的链接。

当我向下滚动网站时,网页中出现的问题不断出现并显示。

当我尝试使用下面的代码抓取这些问题的链接时,在我的例子中,我只得到 5 个链接。 即 - 即使网站上有很多问题,我也只能获得 5 个问题的链接。

是否有任何解决方法来获取网页中存在的尽可能多的问题链接?

from bs4 import BeautifulSoup
import requests

root = 'https://www.quora.com/topic/Graduate-Record-Examination-GRE-1'
headers = {'User-Agent' : 'Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:42.0) Gecko/20100101 Firefox/42.' }
r = requests.get(root,headers=headers)

soup = BeautifulSoup(r.text,'html.parser')

q = soup.find('div',{'class':'paged_list_wrapper'})
no=0
for i in q.find_all('div',{'class':'story_title_container'}):
    t=i.a['href']
    no=no+1
    print(root+t,'\n\n')

Requests 和 BeautifulSoup 无法完成您想要完成的任务。 你需要使用硒。 在这里,我使用 selenium 和 chromedriver 给出了答案。 为你的 chrome 版本下载 chromedriver并安装 selenium pip install -U selenium

import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import csv
browser = webdriver.Chrome(executable_path='/path/to/chromedriver')
browser.get("https://www.quora.com/topic/Graduate-Record-Examination-GRE-1")
time.sleep(1)
elem = browser.find_element_by_tag_name("body")
no_of_pagedowns = 5
while no_of_pagedowns:
    elem.send_keys(Keys.PAGE_DOWN)
    time.sleep(0.2)
    no_of_pagedowns-=1
post_elems =browser.find_elements_by_xpath("//a[@class='question_link']")
for post in post_elems:
    print(post.get_attribute("href"))

如果您使用的是 Windows - executable_path='/path/to/chromedriver.exe'

更改此变量no_of_pagedowns = 5以指定要向下滚动的次数。

我得到以下输出

在此处输入图像描述

标题从页面抓取,格式化后打印。 这是一种方法,我敢肯定有很多方法可以做到这一点,而这只会解决一个问题。

import requests
from bs4 import BeautifulSoup

URL = "https://www.quora.com/Which-Deep-Learning-online-course-is-better-Coursera-specialization-VS-Udacity-Nanodegree-vs-FAST-ai"

response = requests.get(URL)
soup = BeautifulSoup(response.text, 'html.parser')

# grabs the text in the title
question = soup.select_one('title').text
# removes - quora at the end
x = slice(-8) 

print(question[x])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM