Hyper(link) Active
หนึ่งใน attribute ที่สำคัญที่สุดสำหรับการ "web-crawling" คือ URL ของ hyperlink (attribute href) ภายใน tag a ในแบบฝึกหัดนี้ คุณจะได้ดึงข้อมูล hyperlink ดังกล่าว! เราได้สร้างฟังก์ชัน print_attribute ไว้ให้แล้วเพื่อแสดงผลข้อมูลที่ดึงมาจาก XPath ของคุณ สามารถทดสอบ XPath string ใน console ได้เลย
แบบฝึกหัดนี้อ้างอิงโค้ด HTML ต่อไปนี้:
<html>
<body>
<div id="div1" class="class-1">
<p class="class-1 class-2">Hello World!</p>
<div id="div2">
<p id="p2" class="class-2">Choose
<a href="http://datacamp.com">DataCamp!</a>!
</p>
</div>
</div>
<div id="div3" class="class-2">
<p class="class-2">Thanks for Watching!</p>
</div>
</body>
</html>
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Web Scraping ด้วย Python
คำแนะนำการฝึกหัด
- เติมช่องว่างให้ครบเพื่อสร้างตัวแปร
xpathด้านล่าง โดยให้เลือกค่า attributehrefจาก hyperlink ของ DataCamp
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Create an xpath to the href attribute
xpath = '//p[@id=____]/a/____'
# Print out the selection(s); there should be only one
print_attribute( xpath )