Scrapy SgmlLinkExtractor how to define XPath
<p>I want to retreive the cityname and citycode and store it in one string variable. The image shows the precise location:</p>

<p><a href="http://i.stack.imgur.com/PmMcq.png" rel="nofollow"><img src="http://i.stack.imgur.com/PmMcq.png" alt="enter image description here"></a></p>

<p>Google Chrome gave me the following XPath:</p>

<pre><code>//*[@id="page"]/main/div[4]/div[2]/div[1]/div/div/div[1]/div[2]/div/div[1]/div/a[1]/span
</code></pre>

<p>So I defined the following statement in scrapy to get the desired information: </p>

<pre><code>plz = response.xpath('//*[@id="page"]/main/div[4]/div[2]/div[1]/div/div/div[1]/div[2]/div/div[1]/div/a[1]/span/text()').extract()
</code></pre>

<p>However I was not successful, the string remains empty. What XPath definition should I use instead?</p>

<p>Most of the time this occurs, this is because browsers correct invalid HTML. How do you fix this? Inspect the (raw) HTML source and write your own XPath that navigate the DOM with the shortest/simplest query.</p>

<p>I scrape a lot of data off of the web and I've never used an XPath as specific as the one you got from the browser. This is for a few reasons:</p>

<ol>
<li>It will fail quickly on invalid HTML or the most basic of hierarchy changes.</li>
<li>It contains no identifying data for debugging an issue when the website changes.</li>
<li>It's way longer than it should be.</li>
</ol>

<p>Here's an <strong><em>example</em></strong> (there are a lot of different XPath queries you could write to find this data, I'd suggest you learning and re-writing this query so there are common themes for XPath queries throughout your project) query for grabbing that element:</p>

<pre><code>//div[contains(@class, "detail-address")]//h2/following-sibling::span
</code></pre>

<hr>

<p>The other main source of this problem is sites that extensively rely on JS to modify what is shown on the screen. Conveniently, though, this would be debugged the same was as above. As soon as you glance at the HTML returned on page load, you would notice that the data you are querying doesn't exist until JS executes. At that point, you would need to do some sort of <a href="https://en.wikipedia.org/wiki/Headless_browser" rel="nofollow">headless browsing</a>.</p>

<hr>

<p>Since my answer was essentially "write your own XPath" (rather than relying on the browser), I'll leave some sources:</p>

<ul>
<li><a href="http://archive.oreilly.com/pub/a/perl/excerpts/system-admin-with-perl/ten-minute-xpath-utorial.html" rel="nofollow">basic XPath introduction</a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/XPath/Functions" rel="nofollow">list of XPath functions</a></li>
<li><a href="https://chrome.google.com/webstore/detail/xpath-helper/hgimnogjllphhhkhlmebbmlgjoejdpjl?hl=en" rel="nofollow">XPath Chrome extension</a></li>
</ul>

python regex xpath scrapy