我想刮刮,例如,标题的前200个问题下的网页问题。我尝试了以下代码:
import requests
from bs4 import BeautifulSoup
url = "https://www.quora.com/topic/Stack-Overflow-4/all_questions"
print("url")
print(url)
r = requests.get(url) # HTTP request
print("r")
print(r)
html_doc = r.text # Extracts the html
print("html_doc")
print(html_doc)
soup = BeautifulSoup(html_doc, 'lxml') # Create a BeautifulSoup object
print("soup")
print(soup)它给了我一条短信https://pastebin.com/9dSPzAyX。如果我们搜索href='/,我们可以看到html确实包含一些问题的标题。但是,问题是数字不够;实际上,在网页上,用户需要手动向下滚动以触发额外的负载。
有人知道我如何模仿程序“向下滚动”来加载更多的页面内容吗?
发布于 2019-03-05 03:05:41
网页上的无限滚动是基于Javascript功能的。因此,为了找出我们需要访问的URL和要使用的参数,我们需要深入研究在页面内工作的JS代码,或者最好检查浏览器在向下滚动页面时所做的请求。我们可以使用开发工具来研究请求。见quora示例
向下滚动越多,生成的请求就越多。因此,现在您的请求将被执行到该url,而不是普通的url,但请记住,要发送正确的标题和播放负载。
其他更简单的解决方案是使用selenium。
发布于 2019-03-05 03:32:16
无法使用请求找到响应。但你可以用硒。首先在第一次加载时打印出问题的数量,然后发送结束键以模拟向下滚动。在发送完键后,您可以看到从20个问题到40个问题。
在再次加载DOM之前,我使用了driver.implicitly等待5秒,以防脚本在加载DOM之前加载到快速。您可以通过使用含硒的EC来改进。
该页面每个卷轴加载20个问题。因此,如果你想刮100个问题,那么你需要发送结束键5次。
要使用下面的代码,您需要安装chromedriver。http://chromedriver.chromium.org/downloads
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
CHROMEDRIVER_PATH = ""
CHROME_PATH = ""
WINDOW_SIZE = "1920,1080"
chrome_options = Options()
# chrome_options.add_argument("--headless")
chrome_options.add_argument("--window-size=%s" % WINDOW_SIZE)
chrome_options.binary_location = CHROME_PATH
prefs = {'profile.managed_default_content_settings.images':2}
chrome_options.add_experimental_option("prefs", prefs)
url = "https://www.quora.com/topic/Stack-Overflow-4/all_questions"
def scrape(url, times):
if not url.startswith('http'):
raise Exception('URLs need to start with "http"')
driver = webdriver.Chrome(
executable_path=CHROMEDRIVER_PATH,
chrome_options=chrome_options
)
driver.get(url)
counter = 1
while counter <= times:
q_list = driver.find_element_by_class_name('TopicAllQuestionsList')
questions = [x for x in q_list.find_elements_by_xpath('//div[@class="pagedlist_item"]')]
q_len = len(questions)
print(q_len)
html = driver.find_element_by_tag_name('html')
html.send_keys(Keys.END)
wait = WebDriverWait(driver, 5)
time.sleep(5)
questions2 = [x for x in q_list.find_elements_by_xpath('//div[@class="pagedlist_item"]')]
print(len(questions2))
counter += 1
driver.close()
if __name__ == '__main__':
scrape(url, 5)发布于 2019-03-05 03:06:14
https://stackoverflow.com/questions/54994689
复制相似问题