目前出于教育原因正在开发“爬虫”,
一切工作正常,我可以提取 url 和信息并将其保存在 json 文件中,一切都很好......除了
该页面有一个“加载更多”按钮,我需要与之交互,以便爬虫继续寻找更多网址。
这就是我可以利用你们这些出色的男孩和女孩的地方!
关于如何执行此操作有什么建议吗?
我想与“加载更多”按钮进行交互,并将 HTML 信息重新发送到我的爬虫。
真的非常感谢你们的帮助!
网站:http://virali.se/photo/gallery/ http://virali.se/photo/gallery/
用于查找公司名称的示例代码:
def base_spider(self, max_pages, max_CIDS):
url = "http://virali.se/photo/gallery/photog/" # Input URL
for pages in range(0, max_pages):
source_code = requests.get(url) # gets the source_code from the URL
plain_text = source_code.text # Pure text transform for BeautifulSoup
soup = BeautifulSoup(plain_text, "html.parser") # Use HTML parser to read the plain_text var
for article in soup.find_all("article"):
business_name_pattern = re.compile(r"<h1>(.*?)</?h1>")
business_name_raw = str(re.findall(business_name_pattern, str(article)))
business_name_clean = re.sub("[\[\]\'\"]", "", business_name_raw)
self.myprint(business_name_clean) # custom print function for weird chars
此代码仅查找企业名称,但是如果不与网址上的“显示更多结果”按钮进行交互,那么当然,它将耗尽可供搜索的企业名称。
如果您使用开发人员工具(我使用 Chrome)查看该网站,那么您可以看到当您单击“显示更多结果”按钮时会触发 XHR post 请求。
在这种情况下,您可以模拟此请求来收集数据:
with requests.Session() as session:
response = session.post("http://virali.se/photo/gallery/search", data={'start':0})
print(response.content)
“魔力”就在data
的参数session.post
:这是从此偏移量加载图像所需的参数。在上面的例子中0
是您在网站上默认看到的第一组图像。
你可以解析response.content
与美丽汤。
我希望这可以帮助您入门,虽然该示例使用 Python 3,但也可以用 Python 2 以相同的方式解决(不使用with
构造)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)