无法从Quora网页上刮出许多问题

时间:2018-12-22 14:27:03

标签: python web-scraping beautifulsoup

我正在学习BeautifulSoup,并尝试抓取this 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')

2 个答案:

答案 0 :(得分:1)

您要完成的任务无法使用Requests和BeautifulSoup完成。您需要使用硒。 在这里,我用硒和chromedriver给出答案。 Download chromedriver for you chrome version并安装硒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,以指定要向下滚动多少次。

我得到以下输出

enter image description here

答案 1 :(得分:0)

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

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])